<template>
  <div class="homework-detail-page">
    <!-- 返回按钮 -->
    <div class="back-button">
      <button @click="goBack" class="btn-back">← 返回我的作业</button>
    </div>

    <!-- 作业信息卡片 -->
    <div v-if="homeworkInfo" class="homework-info-card">
      <h1 class="homework-title">{{ homeworkInfo.title }}</h1>
      <div class="homework-meta">
        <div class="meta-item">
          <span class="label">开始时间：</span>
          <span class="value">{{ formatDate(homeworkInfo.startTime) }}</span>
        </div>
        <div class="meta-item">
          <span class="label">截止时间：</span>
          <span class="value">{{ formatDate(homeworkInfo.endTime) }}</span>
        </div>
        <div class="meta-item">
          <span class="label">总分：</span>
          <span class="value">{{ calculatedTotalScore }} 分</span>
        </div>
        <div class="meta-item">
          <span class="label">试题数量：</span>
          <span class="value">{{ questions.length }} 题</span>
        </div>
        <div class="meta-item timer-item">
          <span class="label">⏱️ 已用时间：</span>
          <span class="value timer-value">{{ displayTime }}</span>
        </div>
      </div>
      <div v-if="homeworkInfo.description" class="homework-description">
        <h3>作业说明</h3>
        <p>{{ homeworkInfo.description }}</p>
      </div>
    </div>

    <!-- 试题列表 -->
    <div v-if="questions.length > 0" class="questions-section">
      <h2 class="section-title">📝 作业试题</h2>
      
      <div class="questions-layout">
        <aside class="question-nav">
          <div class="nav-header">
            <span class="nav-title">题目列表</span>
            <span class="nav-count">{{ questions.length }} 题</span>
          </div>
          <ul class="question-nav-list">
            <li
              v-for="(question, index) in questions"
              :key="'nav-' + (question.id || index)"
              :class="['question-nav-item', { active: activeQuestionIndex === index }]"
              @click="scrollToQuestion(index, question)"
              :title="question.title || '未命名题目'"
            >
              <span class="item-index">{{ index + 1 }}</span>
              <span
                v-if="hasQuestionScore(question)"
                class="item-score-below"
              >{{ getQuestionScore(question) }}</span>
            </li>
          </ul>
        </aside>

        <div class="questions-list">
          <div
            v-for="(question, index) in questions"
            :key="question.id || ('question-' + index)"
            :id="getQuestionAnchorId(question, index)"
            class="question-card"
          >
          <div class="question-header">
            <div class="header-left">
              <span class="question-number">第 {{ index + 1 }} 题</span>
              <span class="question-difficulty" :class="getDifficultyClass(question.difficulty)">
                {{ question.difficulty }}
              </span>
            </div>
            <button @click="viewQuestionDetail(question, index)" class="view-detail-btn">
              🔍 查看详情
            </button>
          </div>
          
          <h3 class="question-title">{{ question.title || '未命名题目' }}</h3>
          
          <div class="question-info">
            <div class="info-item">
              <span class="label">分值：</span>
              <span class="value">{{ question.score }} 分</span>
            </div>
            <div class="info-item">
              <span class="label">时间限制：</span>
              <span class="value">{{ question.timeLimit }}ms</span>
            </div>
            <div class="info-item">
              <span class="label">内存限制：</span>
              <span class="value">{{ question.memoryLimit }}MB</span>
            </div>
          </div>
          
          <div v-if="question.description" class="question-description">
            <h4>📝 题目描述</h4>
            <p>{{ question.description }}</p>
          </div>
          
          <!-- 🔥 题目描述图片 (questionDescribePicture) -->
          <div v-if="question.questionDescribePicture" class="question-description-image">
            <h4>🖼️ 题目描述图片</h4>
            <img :src="getImageUrl(question.questionDescribePicture)" :alt="question.title + ' 题目描述图片'" @error="handleImageError">
          </div>
          
          <div v-if="question.questionPicture" class="question-image">
            <h4>🖼️ 参考程序结果图</h4>
            <img :src="getImageUrl(question.questionPicture)" :alt="question.title" @error="handleImageError">
          </div>
          
          <div v-if="question.inputFormat" class="question-format">
            <h4>📥 输入格式</h4>
            <p>{{ question.inputFormat }}</p>
          </div>
          
          <div v-if="question.outputFormat" class="question-format">
            <h4>📤 输出格式</h4>
            <!-- 🔥 根据 outputFormat 内容智能判断是文本还是图片 -->
            
            <!-- 如果 outputFormat 包含图片URL，显示图片 -->
            <div v-if="isImageUrl(question.outputFormat)" class="output-image-container">
              <img 
                :src="getImageUrl(question.outputFormat)" 
                :alt="question.title + ' 输出格式图片'"
                class="output-format-image"
                @error="handleImageError"
              >
              <p class="image-caption">输出格式示例图</p>
            </div>
            
            <!-- 否则显示文本 -->
            <p v-else>{{ question.outputFormat }}</p>
          </div>
          
          <div v-if="question.rangeAndPrompt" class="question-format">
            <h4>💡 范围与提示</h4>
            <p>{{ question.rangeAndPrompt }}</p>
          </div>
          
          <!-- 测试用例显示 -->
          <div v-if="question.testCases && Array.isArray(question.testCases) && question.testCases.length > 0" class="question-test-cases">
            <h4>🧪 测试用例</h4>
            <div class="test-cases-grid">
              <div v-for="(testCase, tcIndex) in question.testCases" 
                   :key="'tc-' + tcIndex" 
                   class="test-case-card">
                <div class="test-case-header-small">
                  <span>测试用例 {{ tcIndex + 1 }}</span>
                </div>
                <div class="test-case-body">
                  <div class="test-case-field">
                    <label>输入格式</label>
                    <div class="field-content">{{ testCase.input || '无输入' }}</div>
                  </div>
                  <div class="test-case-field">
                    <label>输出格式</label>
                    <!-- 如果输出是图片URL，显示图片 -->
                    <div v-if="isImageUrl(testCase.expectedOutput)" class="field-image">
                      <img :src="getImageUrl(testCase.expectedOutput)" alt="输出格式图片" @error="handleImageError">
                    </div>
                    <!-- 否则显示文本 -->
                    <div v-else class="field-content">{{ testCase.expectedOutput || '无输出' }}</div>
                  </div>
                </div>
              </div>
            </div>
          </div>
          
          <div v-if="question.testCode" class="question-reference-code">
            <div class="reference-code-header">
              <h4>✅ 参考程序</h4>
              <div class="reference-code-actions">
                <button @click="viewLastSubmit(question, index)" class="last-submit-btn">
                  <i class="fas fa-history"></i>
                  <span>查看上次提交</span>
                </button>
                <button @click="toggleReferenceCode(index)" class="toggle-code-btn">
                  <span v-if="showReferenceCode[index]">🙈 隐藏答案</span>
                  <span v-else>👁️ 查看答案</span>
                </button>
              </div>
            </div>
            
            
            <pre v-show="showReferenceCode[index]"><code>{{ question.testCode }}</code></pre>
            <div v-show="!showReferenceCode[index]" class="code-hidden-hint">
              <i class="fas fa-lock"></i>
              <p>参考程序已隐藏，点击上方按钮查看</p>
            </div>
          </div>
          
          <!-- 在线编译器区域 -->
          <div class="question-editor-section">
            <div class="editor-toggle-header">
              <h4>💻 在线编译器</h4>
              <button @click="toggleEditor(index)" class="toggle-editor-btn">
                <span v-if="showEditor[index]">📤 收起编译器</span>
                <span v-else>📥 打开编译器</span>
              </button>
            </div>
            <div v-show="showEditor[index]" class="editor-container">
              <GocJudge 
                v-if="showEditor[index]"
                :problem="getQuestionWithDetails(question, index)"
                :judgeMode="'strict'"
                :enableImageComparison="true"
                @judge-complete="(result) => onJudgeComplete(result, question)"
                @code-submit="(code) => onCodeSubmit(code, question)"
                @error="onEditorError"
              />
            </div>
          </div>
        </div>
      </div>
    </div>
      
      <!-- 提交作业按钮 - 在所有题目下方 -->
      <div class="submit-homework-section">
        <button @click="submitAllHomework" class="btn-submit-homework" :disabled="isSubmitting" :class="{ 'expired': isHomeworkExpired }">
          <span v-if="isSubmitting">提交中...</span>
          <span v-else-if="isHomeworkExpired">⏰ 作业已截止</span>
          <span v-else>📤 提交作业</span>
        </button>
        <p v-if="isHomeworkExpired" class="expired-hint">作业已超过截止时间，无法提交</p>
      </div>
    </div>

    <!-- 无试题提示 -->
    <div v-else class="no-questions">
      <p>该作业暂无试题</p>
    </div>
    
    <!-- 上次提交代码弹窗 -->
    <div v-if="showLastSubmitDialog" class="modal-overlay" @click="closeLastSubmitDialog">
      <div class="modal-container last-submit-modal" @click.stop>
        <div class="modal-header">
          <div class="modal-title-section">
            <i class="fas fa-history"></i>
            <h3>上次提交的代码</h3>
          </div>
          <button @click="closeLastSubmitDialog" class="modal-close-btn">
            <i class="fas fa-times"></i>
          </button>
        </div>
        
        <div class="modal-body">
          <div v-if="currentLoadingLastSubmit" class="loading-section">
            <i class="fas fa-spinner fa-spin"></i>
            <p>加载中...</p>
          </div>
          
          <div v-else-if="currentLastSubmitData" class="last-submit-content">
            <!-- 提交信息卡片 -->
            <div class="submit-info-section">
              <div class="info-item">
                <span class="label">题目ID：</span>
                <span class="value">{{ currentLastSubmitData.testQuestionId }}</span>
              </div>
              <div class="info-item">
                <span class="label">提交次数：</span>
                <span class="value">{{ currentLastSubmitData.submitCount || 0 }} 次</span>
              </div>
              <div class="info-item">
                <span class="label">最后提交时间：</span>
                <span class="value">{{ formatSubmitTime(currentLastSubmitData.lastSubmitTime) }}</span>
              </div>
            </div>
            
            <!-- 代码展示区域 -->
            <div class="code-display-section">
              <div class="code-display-header">
                <h4>
                  <i class="fas fa-code"></i>
                  提交的代码
                </h4>
                <button @click="copyLastSubmitCode" class="copy-btn-large">
                  <i class="fas fa-copy"></i>
                  复制代码
                </button>
              </div>
              <pre class="large-code-block"><code>{{ currentLastSubmitData.codeContent }}</code></pre>
            </div>
          </div>
          
          <div v-else class="no-data-message">
            <i class="fas fa-inbox"></i>
            <p>暂无提交记录</p>
          </div>
        </div>
        
        <div class="modal-footer">
          <button @click="closeLastSubmitDialog" class="modal-btn secondary">关闭</button>
        </div>
      </div>
    </div>
    
    <!-- 我的提交代码弹窗 -->
    <div v-if="showSubmissionDialog" class="modal-overlay" @click="closeSubmissionDialog">
      <div class="modal-container submission-modal" @click.stop>
        <div class="modal-header">
          <div class="modal-title-section">
            <i class="fas fa-code"></i>
            <h3>我的提交代码</h3>
          </div>
          <button @click="closeSubmissionDialog" class="modal-close-btn">
            <i class="fas fa-times"></i>
          </button>
        </div>
        
        <div class="modal-body">
          <div v-if="loadingSubmission" class="loading-section">
            <i class="fas fa-spinner fa-spin"></i>
            <p>加载中...</p>
          </div>
          
          <div v-else-if="submissionData" class="submission-content">
            <!-- 作业基本信息 -->
            <div class="submission-info-section">
              <div class="info-item">
                <span class="label">作业标题：</span>
                <span class="value">{{ submissionData.homeworkTitle }}</span>
              </div>
              <div class="info-item">
                <span class="label">总分：</span>
                <span class="value score-highlight">{{ submissionData.totalScore }}</span>
              </div>
              <div class="info-item">
                <span class="label">总耗时：</span>
                <span class="value">{{ formatTimeMs(submissionData.totalTime) }}</span>
              </div>
              <div class="info-item">
                <span class="label">提交时间：</span>
                <span class="value">{{ submissionData.submitTime || '未知' }}</span>
              </div>
            </div>
            
            <!-- 每道题的代码 -->
            <div class="questions-code-section">
              <h4 class="section-title">📝 各题目提交代码</h4>
              
              <div v-for="(question, index) in submissionData.questionScores" 
                   :key="question.testQuestionId" 
                   class="question-code-card">
                <div class="code-card-header">
                  <div class="header-left">
                    <span class="question-number">第 {{ index + 1 }} 题</span>
                    <span class="question-name">{{ question.questionName }}</span>
                  </div>
                  <div class="header-right">
                    <span class="score-badge" :class="getScoreBadgeClass(question.score, question.fullScore)">
                      {{ question.score }} / {{ question.fullScore }} 分
                    </span>
                  </div>
                </div>
                
                <div v-if="question.codeContent" class="code-content-wrapper">
                  <div class="code-header">
                    <span class="code-label">提交的代码：</span>
                    <button @click="copyCode(question.codeContent, index)" class="copy-code-btn">
                      <i class="fas fa-copy"></i> 复制代码
                    </button>
                  </div>
                  <pre class="code-block"><code>{{ question.codeContent }}</code></pre>
                </div>
                
                <div v-else class="no-code-message">
                  <i class="fas fa-info-circle"></i>
                  <p>该题未提交代码</p>
                </div>
              </div>
            </div>
          </div>
          
          <div v-else class="no-data-message">
            <i class="fas fa-inbox"></i>
            <p>暂无提交记录</p>
          </div>
        </div>
        
        <div class="modal-footer">
          <button @click="closeSubmissionDialog" class="modal-btn secondary">关闭</button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import GocJudge from '@/components/GocJudge.vue'
import api from '@/api/config'
import * as homeworkApi from '@/api/homework'
import logger from '../utils/logger.js'
import { isStudent } from '@/utils/userIdUtils'

export default {
  name: 'HomeworkDetail',
  components: {
    GocJudge
  },
  data() {
    return {
      homeworkInfo: null,
      questions: [],
      showReferenceCode: {}, // 存储每个题目的参考程序显示状态
      showEditor: {}, // 存储每个题目的编译器显示状态
      isSubmitting: false, // 提交作业的加载状态
      questionScores: {}, // 存储每道题的得分情况
      questionCodes: {}, // 存储每道题的学生代码
      questionDetails: {}, // 存储每个题目的详细信息
      startTime: null, // 作业开始时间
      totalElapsedTime: 0, // 总耗时（毫秒）
      displayTime: '00:00:00', // 显示的计时时间
      timerInterval: null, // 计时器定时器
      showSubmissionDialog: false, // 显示提交代码弹窗
      loadingSubmission: false, // 加载提交数据状态
      submissionData: null, // 提交数据
      showLastSubmitDialog: false, // 显示上次提交代码弹窗
      currentLoadingLastSubmit: false, // 当前加载状态
      currentLastSubmitData: null, // 当前上次提交的数据
      activeQuestionIndex: 0, // 题目导航当前高亮索引
      isProgrammaticScroll: false, // 是否处于代码触发的滚动中
      scrollResetTimer: null, // 稍后重置 programmatic 状态的定时器
      questionNavScores: {} // 左侧导航展示的题目分数（有则显示分数，无则显示序号）
    }
  },
  computed: {
    // 判断当前用户是否为学生
    isStudentUser() {
      const result = isStudent()
      logger.log('👤 [HomeworkDetail] 当前用户是否为学生:', result)
      return result
    },
    
    // 判断作业是否已截止
    isHomeworkExpired() {
      if (!this.homeworkInfo || !this.homeworkInfo.endTime) {
        return false
      }
      
      const endTime = new Date(this.homeworkInfo.endTime).getTime()
      const currentTime = new Date().getTime()
      
      return currentTime > endTime
    },
    
    // 🔥 新增：计算作业总分（所有题目分数之和）
    calculatedTotalScore() {
      if (!this.questions || this.questions.length === 0) {
        return this.homeworkInfo?.totalScore || 0
      }
      
      // 计算所有题目的分数总和
      const total = this.questions.reduce((sum, question) => {
        const score = parseInt(question.score) || 0
        return sum + score
      }, 0)
      
      logger.log('📊 [HomeworkDetail] 计算作业总分:', {
        题目数量: this.questions.length,
        各题分数: this.questions.map(q => q.score),
        总分: total
      })
      
      return total
    }
  },
  watch: {
    questions: {
      handler() {
        this.$nextTick(() => {
          this.updateActiveQuestionByScroll()
        })
      },
      deep: false
    }
  },
  mounted() {
    logger.log('📚 [HomeworkDetail] 页面加载')
    
    // 启动计时器
    this.startTime = Date.now()
    logger.log('⏱️ [HomeworkDetail] 计时器已启动，开始时间:', new Date(this.startTime).toLocaleString())
    
    // 启动显示计时器，每秒更新一次
    this.timerInterval = setInterval(() => {
      this.updateDisplayTime()
    }, 1000)
    
    this.loadHomeworkDetail()
    
    window.addEventListener('scroll', this.updateActiveQuestionByScroll, { passive: true })
  },
  
  beforeUnmount() {
    logger.log('🧹 [HomeworkDetail] 页面即将卸载，清理资源')
    
    // 清除计时器
    if (this.timerInterval) {
      clearInterval(this.timerInterval)
      this.timerInterval = null
      logger.log('⏱️ [HomeworkDetail] 计时器已清除')
    }
    
    // 页面卸载时记录总耗时（如果还没提交）
    if (this.startTime && !this.isSubmitting) {
      this.totalElapsedTime = Date.now() - this.startTime
      logger.log('⏱️ [HomeworkDetail] 页面卸载，总耗时:', this.totalElapsedTime, 'ms')
    }
    
    // 清理localStorage中的作业数据
    localStorage.removeItem('currentHomework')
    
    logger.log('✅ [HomeworkDetail] 页面清理完成')
    
    // 清除滚动监听与定时器
    window.removeEventListener('scroll', this.updateActiveQuestionByScroll)
    if (this.scrollResetTimer) {
      clearTimeout(this.scrollResetTimer)
      this.scrollResetTimer = null
    }
  },
  methods: {
    hasQuestionScore(question) {
      const qid = (question && (question.id || question.testQuestionId || question.questionId)) ?? null
      return qid !== null && (this.questionNavScores[qid] || this.questionNavScores[qid] === 0)
    },
    getQuestionScore(question) {
      const qid = (question && (question.id || question.testQuestionId || question.questionId)) ?? null
      if (qid === null) return ''
      return String(this.questionNavScores[qid] ?? '')
    },

    getQuestionAnchorId(question, index) {
      if (!question) {
        return `question-card-${index}`
      }
      const qid = question.id || question.testQuestionId || question.questionId || index
      return `question-card-${qid}`
    },

    async loadAllLastScores() {
      try {
        if (!this.questions || this.questions.length === 0) return
        const homeworkId = this.$route.params.id || this.$route.query.id
        if (!homeworkId) return
        const tasks = this.questions.map(async (q) => {
          const qid = q.id || q.testQuestionId || q.questionId
          if (!qid) return
          try {
            const resp = await homeworkApi.getQuestionCurrentCode(homeworkId, qid)
            if (resp && resp.code === 0 && resp.data) {
              const scoreVal = parseInt(resp.data.score || 0)
              this.$set ? this.$set(this.questionNavScores, qid, isNaN(scoreVal) ? 0 : scoreVal)
                : (this.questionNavScores[qid] = isNaN(scoreVal) ? 0 : scoreVal)
            }
          } catch (e) {
            // 忽略单题失败
          }
        })
        await Promise.all(tasks)
      } catch (e) {
        // 忽略
      }
    },

    scrollToQuestion(index, question) {
      logger.log('🧭 [HomeworkDetail] 导航跳转题目:', { index, questionId: question?.id })
      this.activeQuestionIndex = index
      this.isProgrammaticScroll = true
      if (this.scrollResetTimer) {
        clearTimeout(this.scrollResetTimer)
        this.scrollResetTimer = null
      }

      const targetId = this.getQuestionAnchorId(question, index)
      this.$nextTick(() => {
        const targetEl = document.getElementById(targetId)
        if (targetEl) {
          const headerOffset = 80
          const elementPosition = targetEl.getBoundingClientRect().top + window.pageYOffset
          const offsetPosition = Math.max(elementPosition - headerOffset, 0)

          window.scrollTo({
            top: offsetPosition,
            behavior: 'smooth'
          })
        }

        this.scrollResetTimer = setTimeout(() => {
          this.isProgrammaticScroll = false
          this.scrollResetTimer = null
        }, 600)
      })
    },

    updateActiveQuestionByScroll() {
      if (this.isProgrammaticScroll) return
      if (!this.questions || this.questions.length === 0) return

      const headerOffset = 120
      let nearestIndex = this.activeQuestionIndex || 0
      let closestDistance = Number.POSITIVE_INFINITY

      this.questions.forEach((question, index) => {
        const el = document.getElementById(this.getQuestionAnchorId(question, index))
        if (!el) return

        const rect = el.getBoundingClientRect()
        const distance = Math.abs(rect.top - headerOffset)

        if (rect.bottom > headerOffset && rect.top < window.innerHeight) {
          if (distance < closestDistance) {
            closestDistance = distance
            nearestIndex = index
          }
        } else if (closestDistance === Number.POSITIVE_INFINITY && rect.top <= headerOffset) {
          closestDistance = distance
          nearestIndex = index
        }
      })

      if (nearestIndex !== this.activeQuestionIndex) {
        this.activeQuestionIndex = nearestIndex
      }
    },

    async loadHomeworkDetail() {
      try {
        // 从localStorage获取作业详情
        const homeworkData = localStorage.getItem('currentHomework')
        
        if (homeworkData) {
          this.homeworkInfo = JSON.parse(homeworkData)
          logger.log('✅ [HomeworkDetail] 作业信息:', this.homeworkInfo)
          
          // 解析试题列表
          if (this.homeworkInfo.questions && Array.isArray(this.homeworkInfo.questions)) {
            logger.log('📝 [HomeworkDetail] 基础试题数量:', this.homeworkInfo.questions.length)
            logger.log('📋 [HomeworkDetail] 基础试题信息:', this.homeworkInfo.questions)
            
            // 先格式化基础题目信息，让页面先显示出来
            this.questions = this.homeworkInfo.questions.map(q => this.formatQuestion(q))
            logger.log('✅ [HomeworkDetail] 基础题目列表已加载')
            this.activeQuestionIndex = 0
            
            // 🔥 自动为每个题目加载详细信息
            logger.log('🚀 [HomeworkDetail] 开始自动加载所有题目详情...')
            for (let i = 0; i < this.questions.length; i++) {
              const question = this.questions[i]
              logger.log(`📥 [HomeworkDetail] 自动加载第${i+1}题详情...`)
              
              // 自动调用查看详情方法（不显示alert提示）
              await this.autoLoadQuestionDetail(question, i)
            }
            
            logger.log('✅ [HomeworkDetail] 所有题目详情自动加载完成')
            
            // 🔥 并行拉取所有题目的上次分数，填充左侧导航
            this.loadAllLastScores()
            
            // 🔥 自动打开第1题编译器
            setTimeout(() => {
              try {
                if (this.questions && this.questions.length > 0) {
                  this.toggleEditor(0)
                }
              } catch (e) {
                logger.warn('⚠️ [HomeworkDetail] 自动打开第1题编译器失败:', e)
              }
            }, 200)
          } else {
            logger.warn('⚠️ [HomeworkDetail] 没有找到试题列表')
          }
        } else {
          logger.warn('⚠️ [HomeworkDetail] 没有找到作业数据')
          alert('未找到作业信息，请重新选择作业')
          this.goBack()
        }
      } catch (error) {
        logger.error('❌ [HomeworkDetail] 加载作业详情失败:', error)
        alert('加载作业详情失败')
        this.goBack()
      }
    },
    
    // 🔥 新增：自动加载题目详情（静默加载，不显示alert）
    async autoLoadQuestionDetail(question, index) {
      try {
        logger.log('📥 [HomeworkDetail] 自动加载题目详情，索引:', index)
        
        // 获取题目ID
        const questionId = question.testQuestionId || question.questionId || question.id
        
        if (!questionId) {
          logger.warn('⚠️ [HomeworkDetail] 题目ID不存在，跳过')
          return
        }
        
        logger.log('🆔 [HomeworkDetail] 题目ID:', questionId)
        
        // 动态导入API
        const api = await import('@/api/config')
        
        // 调用接口获取题目详情
        const response = await api.default.get('/goc/testQuestion/findById', {
          params: {
            id: questionId
          }
        })
        
        logger.log('✅ [HomeworkDetail] 题目详情响应:', response)
        
        // 处理响应数据
        if (response && response.code === 0 && response.data) {
          logger.log('✅ [HomeworkDetail] 题目详情获取成功')
          
          // 合并数据
          const mergedData = {
            ...question,
            ...response.data
          }
          
          // 格式化并更新题目
          const detailedQuestion = this.formatQuestion(mergedData)
          this.questions[index] = detailedQuestion
          this.questionDetails[index] = detailedQuestion
          
          logger.log(`✅ [HomeworkDetail] 第${index+1}题详情已自动加载`)
        } else {
          logger.warn('⚠️ [HomeworkDetail] 题目详情数据无效')
        }
      } catch (error) {
        logger.error('❌ [HomeworkDetail] 自动加载题目详情失败:', error)
        // 静默失败，不打断用户体验
      }
    },
    
    formatQuestion(question) {
      logger.log('🔄 [HomeworkDetail] 格式化题目:', question)
      logger.log('🔍 [HomeworkDetail] 原始题目中的strict:', question.strict)
      logger.log('🔍 [HomeworkDetail] strict类型:', typeof question.strict)
      
      // 将后端返回的题目格式转换为显示需要的格式
      const formatted = {
        // 保留所有可能的ID字段
        id: question.id || question.questionId || question.testQuestionId,
        testQuestionId: question.testQuestionId || question.id || question.questionId,
        questionId: question.questionId || question.id || question.testQuestionId,
        
        // 题目基本信息（注意后端字段名）
        title: question.questionName || question.title || question.name || '未命名题目',
        description: question.questionDescribe || question.description || question.content || question.questionDescription || '',
        
        // 难度映射（后端是数字1-3）
        difficulty: this.mapDifficulty(question.difficulty),
        
        // 限制条件
        timeLimit: question.timeLimit || 5000,
        memoryLimit: question.memoryLimit || 128,
        spaceLimit: question.spaceLimitation || 268435456,
        
        // 代码相关
        starterCode: question.starterCode || question.template || question.codeTemplate || question.initialCode || `int main() {
    // 在这里编写你的代码

    return 0;
}`,
        testCode: question.testCode || '', // 参考代码
        
        // 格式说明
        inputFormat: question.inputFormat || '',
        outputFormat: question.outputFormat || '', // 原字段保留兼容
        outputType: question.outputType || '', // 新增：文本形式的输出格式
        outputFile: question.outputFile || '', // 新增：图片形式的输出格式
        rangeAndPrompt: question.rangeAndPrompt || '',
        
        // 测试用例（testCases可能是字符串）
        testCases: this.formatTestCases(
          Array.isArray(question.testCaseList) ? question.testCaseList :
          Array.isArray(question.testCases) ? question.testCases :
          typeof question.testCases === 'string' ? this.parseTestCasesString(question.testCases) : []
        ),
        testCasesRaw: question.testCases, // 保留原始值
        
        // 分数和其他
        score: question.score || question.questionScore || question.point || 10,
        sortOrder: question.sortOrder,
        
        // 图片
        questionPicture: question.questionPicture || '',
        questionDescribePicture: question.questionDescribePicture || '', // 🔥 题目描述图片
        
        // 题目类型和标签
        questionType: question.questionType,
        label: question.label || '',
        courseLevelId: question.courseLevelId,
        
        // 统计信息
        submissionQuantity: question.submissionQuantity || 0,
        byQuantity: question.byQuantity || 0,
        
        // 其他
        isPublic: question.isPublic,
        createTime: question.createTime,
        updateTime: question.updateTime,
        
        // 🔥 新增：严格判题参数
        strict: question.strict !== undefined && question.strict !== null ? question.strict : '0'
      }
      
      logger.log('✅ [HomeworkDetail] 格式化完成:', formatted)
      logger.log('🔍 [HomeworkDetail] 格式化后的strict:', formatted.strict)
      logger.log('🔍 [HomeworkDetail] 格式化后strict类型:', typeof formatted.strict)
      logger.log('🆔 [HomeworkDetail] ID字段:', {
        id: formatted.id,
        testQuestionId: formatted.testQuestionId,
        questionId: formatted.questionId
      })
      return formatted
    },
    
    mapDifficulty(difficulty) {
      // 将数字难度映射为文字
      if (typeof difficulty === 'number') {
        const difficultyMap = {
          1: '简单',
          2: '中等',
          3: '困难'
        }
        return difficultyMap[difficulty] || '简单'
      }
      return difficulty || '简单'
    },
    
    // 解析测试用例JSON字符串
    parseTestCasesString(testCasesStr) {
      logger.log('🔄 [HomeworkDetail] 解析测试用例字符串:', testCasesStr)
      
      if (!testCasesStr || testCasesStr === '{}' || testCasesStr === '[]') {
        logger.log('⚠️ [HomeworkDetail] 测试用例字符串为空或无效')
        return []
      }
      
      try {
        const parsed = JSON.parse(testCasesStr)
        logger.log('✅ [HomeworkDetail] 测试用例解析成功:', parsed)
        
        if (Array.isArray(parsed)) {
          return parsed
        } else if (parsed && typeof parsed === 'object') {
          return [parsed]
        } else {
          return []
        }
      } catch (error) {
        logger.error('❌ [HomeworkDetail] 测试用例JSON解析失败:', error)
        return []
      }
    },
    
    formatTestCases(testCases) {
      logger.log('🔄 [HomeworkDetail] 格式化测试用例:', testCases)
      
      // 格式化测试用例
      if (!Array.isArray(testCases) || testCases.length === 0) {
        logger.log('⚠️ [HomeworkDetail] 测试用例为空，使用默认值')
        return [{
          input: '无输入',
          expectedOutput: '请查看题目描述',
          expectedTrace: [],
          score: 100
        }]
      }
      
      const formatted = testCases.map((tc, index) => {
        logger.log(`🔍 [HomeworkDetail] 处理测试用例 ${index + 1}:`, tc)
        
        return {
          input: tc.input || tc.inputData || '无输入',
          expectedOutput: tc.expectedOutput || tc.output || tc.outputData || tc.expected || '',
          expectedTrace: tc.expectedTrace || tc.trace || tc.traceData || [],
          score: tc.score || tc.point || (100 / testCases.length)
        }
      })
      
      logger.log('✅ [HomeworkDetail] 测试用例格式化完成:', formatted)
      return formatted
    },
    
    getDifficultyClass(difficulty) {
      const difficultyMap = {
        '简单': 'difficulty-easy',
        '简单题': 'difficulty-easy',
        '中等': 'difficulty-medium',
        '中等题': 'difficulty-medium',
        '困难': 'difficulty-hard',
        '困难题': 'difficulty-hard'
      }
      return difficultyMap[difficulty] || 'difficulty-easy'
    },
    
    async viewQuestionDetail(question, index) {
      try {
        logger.log('🔍 [HomeworkDetail] ========== 开始查看题目详情 ==========')
        logger.log('📝 [HomeworkDetail] 题目信息:', question)
        logger.log('📝 [HomeworkDetail] 题目索引:', index)
        
        // 获取题目ID - 优先使用testQuestionId
        logger.log('🔍 [HomeworkDetail] 步骤1: 获取题目ID...')
        const questionId = question.testQuestionId || question.questionId || question.id
        
        logger.log('🔍 [HomeworkDetail] ID查找过程:')
        logger.log('  - question.testQuestionId:', question.testQuestionId)
        logger.log('  - question.questionId:', question.questionId)
        logger.log('  - question.id:', question.id)
        logger.log('🆔 [HomeworkDetail] 最终题目ID:', questionId)
        logger.log('🆔 [HomeworkDetail] ID类型:', typeof questionId)
        
        if (!questionId) {
          logger.error('❌ [HomeworkDetail] 题目ID不存在')
          alert('题目ID不存在，无法查看详情')
          return
        }
        
        logger.log('✅ [HomeworkDetail] 步骤1完成: 题目ID获取成功')
        
        // 动态导入API
        logger.log('🔍 [HomeworkDetail] 步骤2: 导入API模块...')
        const api = await import('@/api/config')
        logger.log('✅ [HomeworkDetail] 步骤2完成: API模块导入成功')
        logger.log('📦 [HomeworkDetail] api对象:', api)
        logger.log('📦 [HomeworkDetail] api.default:', api.default)
        
        logger.log('🌐 [HomeworkDetail] 步骤3: 准备调用题目详情接口')
        logger.log('🌐 [HomeworkDetail] 接口地址: /goc/testQuestion/findById')
        logger.log('🌐 [HomeworkDetail] 请求参数:', { id: questionId })
        
        // 从全局配置获取 API_BASE_URL
        const GLOBAL_CONFIG = window.GLOBAL_CONFIG || {}
        const baseURL = GLOBAL_CONFIG.API_BASE_URL || 'http://localhost:8000'
        logger.log('🌐 [HomeworkDetail] 配置的baseURL:', baseURL)
        logger.log('🌐 [HomeworkDetail] 完整URL:', baseURL + '/goc/testQuestion/findById?id=' + questionId)
        
        // 调用接口获取题目详情
        logger.log('🚀 [HomeworkDetail] 步骤4: 开始发送HTTP请求...')
        const response = await api.default.get('/goc/testQuestion/findById', {
          params: {
            id: questionId
          }
        })
        
        logger.log('✅ [HomeworkDetail] 步骤4完成: HTTP请求成功')
        logger.log('📦 [HomeworkDetail] 完整响应:', response)
        logger.log('📦 [HomeworkDetail] 响应code:', response?.code)
        logger.log('📦 [HomeworkDetail] 响应message:', response?.message)
        logger.log('📦 [HomeworkDetail] 响应data:', response?.data)
        
        // 处理响应数据
        logger.log('🔍 [HomeworkDetail] 步骤5: 处理响应数据...')
        if (response && response.code === 0 && response.data) {
          logger.log('✅ [HomeworkDetail] 响应数据有效')
          logger.log('📦 [HomeworkDetail] 题目详细数据:', response.data)
          
          // 更新题目信息
          logger.log('🔄 [HomeworkDetail] 步骤6: 合并题目数据...')
          const mergedData = {
            ...question,
            ...response.data
          }
          logger.log('📦 [HomeworkDetail] 合并后的数据:', mergedData)
          
          logger.log('🔄 [HomeworkDetail] 步骤7: 格式化题目数据...')
          const detailedQuestion = this.formatQuestion(mergedData)
          logger.log('📦 [HomeworkDetail] 格式化后的题目:', detailedQuestion)
          
          // 更新questions数组中的对应题目（Vue 3直接赋值即可）
          logger.log('🔄 [HomeworkDetail] 步骤8: 更新Vue数组...')
          this.questions[index] = detailedQuestion
          
          // 🔥 新增：保存题目详细信息（包含strict）
          this.questionDetails[index] = detailedQuestion
          logger.log('🔥 [HomeworkDetail] 保存题目详细信息:', detailedQuestion)
          logger.log('🔥 [HomeworkDetail] strict值:', detailedQuestion.strict)
          logger.log('🔥 [HomeworkDetail] strict类型:', typeof detailedQuestion.strict)
          
          logger.log('✅ [HomeworkDetail] 题目信息已更新')
          logger.log('📋 [HomeworkDetail] 更新后的questions数组:', this.questions)
          logger.log('🎉 [HomeworkDetail] ========== 查看详情完成 ==========')
        } else {
          const errorMsg = response?.message || '获取题目详情失败'
          logger.error('❌ [HomeworkDetail] 获取失败:', errorMsg)
          logger.error('❌ [HomeworkDetail] 响应数据无效:', { code: response?.code, hasData: !!response?.data })
          
          if (this.$message && this.$message.error) {
            this.$message.error(errorMsg)
          } else {
            alert(errorMsg)
          }
        }
      } catch (error) {
        logger.error('❌❌❌ [HomeworkDetail] 发生异常 ❌❌❌')
        logger.error('❌ [HomeworkDetail] 错误对象:', error)
        logger.error('❌ [HomeworkDetail] 错误消息:', error.message)
        logger.error('❌ [HomeworkDetail] 错误堆栈:', error.stack)
        logger.error('❌ [HomeworkDetail] 错误响应:', error.response)
        
        let errorMsg = '获取题目详情失败'
        if (error.response?.data?.message) {
          errorMsg = error.response.data.message
          logger.error('❌ [HomeworkDetail] 后端错误消息:', errorMsg)
        } else if (error.message) {
          errorMsg = error.message
          logger.error('❌ [HomeworkDetail] 前端错误消息:', errorMsg)
        }
        
        alert(errorMsg)
      }
    },
    
    toggleReferenceCode(index) {
      // 检查是否为学生用户
      if (this.isStudentUser) {
        // 学生没有权限查看答案
        logger.warn(`⚠️ [HomeworkDetail] 学生用户无权查看题目 ${index + 1} 的参考答案`)
        
        // 显示权限不足提示
        if (this.$message?.warning) {
          this.$message.warning('权限不足：学生用户无法查看参考答案')
        } else {
          alert('权限不足：学生用户无法查看参考答案')
        }
        return
      }
      
      // 非学生用户可以切换显示状态
      this.showReferenceCode[index] = !this.showReferenceCode[index]
      logger.log(`🔄 [HomeworkDetail] 切换题目 ${index + 1} 的参考程序显示状态:`, this.showReferenceCode[index])
      
      // 强制更新视图（Vue 3响应式）
      this.$forceUpdate()
    },
    
    // 查看上次提交的代码
    async viewLastSubmit(question, index) {
      logger.log('📜 [HomeworkDetail] 查看上次提交代码:', question)
      
      try {
        // 获取作业ID和题目ID
        const homeworkId = this.$route.params.id || this.$route.query.id
        const testQuestionId = question.id || question.testQuestionId || question.questionId
        
        logger.log('📋 [HomeworkDetail] 查看上次提交参数:')
        logger.log('  - $route.params.id:', this.$route.params.id)
        logger.log('  - $route.query.id:', this.$route.query.id)
        logger.log('  - 最终作业ID:', homeworkId)
        logger.log('  - 题目ID:', testQuestionId)
        logger.log('  - 题目索引:', index)
        
        if (!homeworkId || !testQuestionId) {
          const msg = '参数获取失败：作业ID或题目ID为空'
          this.$message?.error?.(msg) || alert(msg)
          return
        }
        
        // 显示弹窗并设置加载状态
        this.showLastSubmitDialog = true
        this.currentLoadingLastSubmit = true
        this.currentLastSubmitData = null
        
        // 调用API获取上次提交代码
        logger.log('🔍 [HomeworkDetail] 正在获取上次提交代码...')
        const response = await homeworkApi.getQuestionCurrentCode(homeworkId, testQuestionId)
        
        logger.log('✅ [HomeworkDetail] 上次提交代码获取成功:', response)
        
        // 处理响应数据
        if (response && response.code === 0 && response.data) {
          this.currentLastSubmitData = response.data
          logger.log('✅ [HomeworkDetail] 上次提交代码加载成功:', this.currentLastSubmitData)
        } else {
          const errorMsg = response?.message || '获取上次提交代码失败'
          logger.error('❌ [HomeworkDetail] 获取失败:', errorMsg)
          this.$message?.error?.(errorMsg) || alert(errorMsg)
          this.currentLastSubmitData = null
        }
        
      } catch (error) {
        logger.error('❌ [HomeworkDetail] 查看上次提交失败:', error)
        
        let errorMsg = '获取上次提交代码失败'
        if (error.response && error.response.data && error.response.data.message) {
          errorMsg = error.response.data.message
        } else if (error.message) {
          errorMsg = error.message
        }
        
        this.$message?.error?.(errorMsg) || alert(errorMsg)
        this.currentLastSubmitData = null
      } finally {
        this.currentLoadingLastSubmit = false
      }
    },
    
    // 关闭上次提交代码弹窗
    closeLastSubmitDialog() {
      logger.log('🔒 [HomeworkDetail] 关闭上次提交代码弹窗')
      this.showLastSubmitDialog = false
      this.currentLastSubmitData = null
    },
    
    // 复制上次提交的代码
    copyLastSubmitCode() {
      logger.log('📋 [HomeworkDetail] 复制上次提交的代码')
      
      const code = this.currentLastSubmitData?.codeContent
      
      if (!code) {
        const msg = '没有代码可复制'
        this.$message?.warning?.(msg) || alert(msg)
        return
      }
      
      // 创建临时textarea元素
      const textarea = document.createElement('textarea')
      textarea.value = code
      textarea.style.position = 'fixed'
      textarea.style.opacity = '0'
      document.body.appendChild(textarea)
      
      try {
        // 选择并复制
        textarea.select()
        document.execCommand('copy')
        
        logger.log('✅ [HomeworkDetail] 代码已复制到剪贴板')
        
        // 🔥 显示复制成功提示（1秒后自动关闭）
        if (this.$message && this.$message.success) {
          this.$message.success({
            message: '已复制',
            duration: 1000
          })
        } else {
          this.showAutoCloseMessage('已复制')
        }
      } catch (err) {
        logger.error('❌ [HomeworkDetail] 复制失败:', err)
        const msg = '复制失败，请手动复制'
        this.$message?.error?.(msg) || alert(msg)
      } finally {
        // 移除临时元素
        document.body.removeChild(textarea)
      }
    },
    
    // 格式化提交时间
    formatSubmitTime(timeStr) {
      if (!timeStr) return '未知'
      
      try {
        const date = new Date(timeStr)
        const year = date.getFullYear()
        const month = String(date.getMonth() + 1).padStart(2, '0')
        const day = String(date.getDate()).padStart(2, '0')
        const hours = String(date.getHours()).padStart(2, '0')
        const minutes = String(date.getMinutes()).padStart(2, '0')
        const seconds = String(date.getSeconds()).padStart(2, '0')
        
        return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
      } catch (error) {
        logger.error('❌ [HomeworkDetail] 时间格式化失败:', error)
        return timeStr
      }
    },
    
    // 查看我的提交代码
    async viewMySubmission() {
      logger.log('👁️ [HomeworkDetail] 查看我的提交代码')
      
      try {
        const homeworkId = this.$route.params.id || this.$route.query.id
        
        if (!homeworkId) {
          const msg = '作业ID获取失败'
          this.$message?.error?.(msg) || alert(msg)
          return
        }
        
        this.showSubmissionDialog = true
        this.loadingSubmission = true
        this.submissionData = null
        
        logger.log('🔍 [HomeworkDetail] 正在获取作业成绩数据...')
        logger.log('  - 作业ID:', homeworkId)
        
        // 调用API获取作业成绩
        const response = await api.get('/goc/homework/myHomeworkScore', {
          params: {
            homeworkId: homeworkId
          }
        })
        
        logger.log('✅ [HomeworkDetail] 作业成绩数据获取成功:', response)
        
        if (response && response.code === 0 && response.data) {
          this.submissionData = response.data
          logger.log('✅ [HomeworkDetail] 提交数据加载成功:', this.submissionData)
        } else {
          const errorMsg = response?.message || '获取提交数据失败'
          logger.error('❌ [HomeworkDetail] 获取失败:', errorMsg)
          this.$message?.error?.(errorMsg) || alert(errorMsg)
          this.submissionData = null
        }
        
      } catch (error) {
        logger.error('❌ [HomeworkDetail] 查看提交失败:', error)
        
        let errorMsg = '获取提交数据失败'
        if (error.response && error.response.data && error.response.data.message) {
          errorMsg = error.response.data.message
        } else if (error.message) {
          errorMsg = error.message
        }
        
        this.$message?.error?.(errorMsg) || alert(errorMsg)
        this.submissionData = null
      } finally {
        this.loadingSubmission = false
      }
    },
    
    // 关闭提交代码弹窗
    closeSubmissionDialog() {
      logger.log('🔒 [HomeworkDetail] 关闭提交代码弹窗')
      this.showSubmissionDialog = false
      this.submissionData = null
    },
    
    // 复制代码
    copyCode(code, index) {
      logger.log('📋 [HomeworkDetail] 复制代码，题目索引:', index)
      
      if (!code) {
        const msg = '没有代码可复制'
        this.$message?.warning?.(msg) || alert(msg)
        return
      }
      
      // 创建临时textarea元素
      const textarea = document.createElement('textarea')
      textarea.value = code
      textarea.style.position = 'fixed'
      textarea.style.opacity = '0'
      document.body.appendChild(textarea)
      
      try {
        // 选择并复制
        textarea.select()
        document.execCommand('copy')
        
        logger.log('✅ [HomeworkDetail] 代码已复制到剪贴板')
        
        // 🔥 显示复制成功提示（1秒后自动关闭）
        if (this.$message && this.$message.success) {
          this.$message.success({
            message: '已复制',
            duration: 1000
          })
        } else {
          this.showAutoCloseMessage('已复制')
        }
      } catch (err) {
        logger.error('❌ [HomeworkDetail] 复制失败:', err)
        const msg = '复制失败，请手动复制'
        this.$message?.error?.(msg) || alert(msg)
      } finally {
        // 移除临时元素
        document.body.removeChild(textarea)
      }
    },
    
    // 格式化时间（毫秒转可读格式）
    formatTimeMs(ms) {
      if (!ms || ms === 0) return '0秒'
      
      const hours = Math.floor(ms / 3600000)
      const minutes = Math.floor((ms % 3600000) / 60000)
      const seconds = Math.floor((ms % 60000) / 1000)
      
      const parts = []
      if (hours > 0) parts.push(`${hours}小时`)
      if (minutes > 0) parts.push(`${minutes}分钟`)
      if (seconds > 0) parts.push(`${seconds}秒`)
      
      return parts.length > 0 ? parts.join(' ') : '0秒'
    },
    
    // 获取成绩标记样式
    getScoreBadgeClass(score, fullScore) {
      if (!fullScore || fullScore === 0) return 'score-zero'
      
      const percentage = (score / fullScore) * 100
      
      if (percentage >= 90) return 'score-excellent'
      if (percentage >= 75) return 'score-good'
      if (percentage >= 60) return 'score-pass'
      if (percentage > 0) return 'score-fail'
      return 'score-zero'
    },
    
    async toggleEditor(index) {
      try {
        // 确保 questionDetails 对象存在
        if (!this.questionDetails) {
          this.questionDetails = {}
        }
        
        // 🔥 如果是打开编辑器（从关闭到打开）
        if (!this.showEditor[index]) {
          const question = this.questions[index]
          
          logger.log(`💻 [HomeworkDetail] 准备打开题目 ${index + 1} 的编辑器`)
          
          // 1. 如果没有题目详细信息，则静默获取
          if (!this.questionDetails[index]) {
            logger.log('🔥 [HomeworkDetail] 编辑器打开但无题目详细信息，静默获取...')
            if (question) {
              await this.loadQuestionDetailSilently(question, index)
            }
          }
          
          // 2. 🔥 先加载上次提交的代码（在打开编辑器之前）
          await this.loadLastSubmitCodeForEditor(question, index)
          
          // 3. 等待一个渲染周期，确保数据已更新
          await this.$nextTick()
          
          // 4. 再打开编辑器
          this.showEditor[index] = true
          logger.log(`✅ [HomeworkDetail] 题目 ${index + 1} 的编辑器已打开`)
        } else {
          // 关闭编辑器
          this.showEditor[index] = false
          logger.log(`📤 [HomeworkDetail] 题目 ${index + 1} 的编辑器已收起`)
        }
        
        // 强制更新视图
        this.$forceUpdate()
      } catch (error) {
        logger.error('❌ [HomeworkDetail] toggleEditor 发生错误:', error)
        // 如果发生错误，确保 showEditor 状态正确
        this.showEditor[index] = false
      }
    },
    
    onJudgeComplete(result, question) {
      logger.log('✅ [HomeworkDetail] 判题完成:', result)
      logger.log('📋 [HomeworkDetail] 题目信息:', question)
      
      // 存储判题结果，用于提交作业（包括图片对比的得分）
      if (result && question && question.id) {
        const questionId = question.id
        // 得分可能来自：
        // 1. 图片对比：result.score（后端返回 data.score）
        // 2. 代码判题：result.totalScore
        const score = result.score || result.totalScore || 0
        // 🔥 同步更新左侧题目导航中的分数
        this.questionNavScores[questionId] = parseInt(score) || 0
        
        // 判断是否是图片对比的结果
        const isImageComparison = Object.prototype.hasOwnProperty.call(result, 'similar')
        
        this.questionScores[questionId] = {
          score: score,
          correctCount: result.correctCount || 0,
          totalQuestions: result.totalQuestions || 0,
          correctRatio: result.correctRatio || 0,
          timeSpent: result.timeSpent || 0,
          isImageComparison: isImageComparison,
          similar: result.similar || null
        }
        
        logger.log('💾 [HomeworkDetail] 保存题目得分:')
        logger.log('  - 题目ID:', questionId)
        logger.log('  - 题目标题:', question.title || '未知')
        logger.log('  - 得分:', score)
        logger.log('  - 判题类型:', isImageComparison ? '图片对比' : '代码判题')
        if (isImageComparison) {
          logger.log('  - 图片相似度:', result.similar ? '相似' : '不相似')
        }
        logger.log('  - 完整数据:', this.questionScores[questionId])
        logger.log('💾 [HomeworkDetail] 当前所有题目得分:', this.questionScores)
        
        // 🔥 判题完成后自动提交作业
        logger.log('🚀 [HomeworkDetail] 判题完成，准备自动提交作业...')
        this.autoSubmitHomework(questionId)
      } else {
        logger.warn('⚠️ [HomeworkDetail] 判题结果或题目信息缺失')
        logger.warn('  - result:', result)
        logger.warn('  - question:', question)
      }
    },
    
    onCodeSubmit(code, question) {
      logger.log('📝 [HomeworkDetail] 代码提交:', code)
      logger.log('📋 [HomeworkDetail] 题目信息:', question)
      logger.log('📋 [HomeworkDetail] code类型:', typeof code)
      
      // 保存学生的代码，用于提交作业
      if (question && question.id && code) {
        const questionId = question.id
        
        // 🔥 处理代码格式：如果是对象，提取 code 字段；如果是字符串，直接使用
        let codeContent = ''
        if (typeof code === 'object') {
          // code 是对象，可能包含 {problemId, code, result} 等字段
          codeContent = code.code || code.codeContent || ''
          logger.log('📋 [HomeworkDetail] code是对象，提取code字段:', codeContent ? '成功' : '失败')
        } else if (typeof code === 'string') {
          // code 是字符串，直接使用
          codeContent = code
          logger.log('📋 [HomeworkDetail] code是字符串，直接使用')
        }
        
        this.questionCodes[questionId] = codeContent
        
        logger.log('💾 [HomeworkDetail] 保存学生代码:')
        logger.log('  - 题目ID:', questionId)
        logger.log('  - 题目标题:', question.title || '未知')
        logger.log('  - 代码类型:', typeof codeContent)
        logger.log('  - 代码长度:', codeContent.length, '字符')
        if (codeContent.length > 0) {
          logger.log('  - 代码预览:', codeContent.substring(0, 50) + '...')
        }
        logger.log('💾 [HomeworkDetail] 当前所有题目代码数量:', Object.keys(this.questionCodes).length)
      } else {
        logger.warn('⚠️ [HomeworkDetail] 代码或题目信息缺失，无法保存')
        logger.warn('  - question:', question)
        logger.warn('  - code:', code)
      }
    },
    
    onEditorError(error) {
      logger.error('❌ [HomeworkDetail] 编译器错误:', error)
      // 可以在这里处理错误，比如显示错误提示
    },
    
    // 更新显示的计时时间
    updateDisplayTime() {
      if (!this.startTime) return
      
      const elapsed = Date.now() - this.startTime
      const hours = Math.floor(elapsed / 3600000)
      const minutes = Math.floor((elapsed % 3600000) / 60000)
      const seconds = Math.floor((elapsed % 60000) / 1000)
      
      this.displayTime = `${String(hours).padStart(2, '0')}:${String(minutes).padStart(2, '0')}:${String(seconds).padStart(2, '0')}`
    },
    
    // 提交作业（提交所有题目）
    async submitAllHomework() {
      try {
        // 🔥 检查作业是否已截止
        if (this.homeworkInfo && this.homeworkInfo.endTime) {
          const endTime = new Date(this.homeworkInfo.endTime).getTime()
          const currentTime = new Date().getTime()
          
          logger.log('⏰ [HomeworkDetail] 截止时间检查:')
          logger.log('  - 截止时间:', this.homeworkInfo.endTime)
          logger.log('  - 当前时间:', new Date().toLocaleString())
          logger.log('  - 是否已截止:', currentTime > endTime)
          
          if (currentTime > endTime) {
            logger.warn('⚠️ [HomeworkDetail] 作业已截止，无法提交')
            
            if (this.$message && this.$message.warning) {
              this.$message.warning('作业已截止，无法提交')
            } else {
              alert('⚠️ 作业已截止，无法提交')
            }
            return
          }
        }
        
        // 确认提交
        if (!confirm('确定要提交作业吗？提交后将无法修改。')) {
          return
        }
        
        this.isSubmitting = true
        logger.log('📤 [HomeworkDetail] 开始提交作业')
        
        // 计算总耗时（从进入页面到点击提交的时间）
        if (this.startTime) {
          this.totalElapsedTime = Date.now() - this.startTime
          logger.log('⏱️ [HomeworkDetail] 作业总耗时:', this.totalElapsedTime, 'ms')
          logger.log('⏱️ [HomeworkDetail] 作业总耗时（秒）:', (this.totalElapsedTime / 1000).toFixed(2), 's')
          logger.log('⏱️ [HomeworkDetail] 作业总耗时（分钟）:', (this.totalElapsedTime / 60000).toFixed(2), 'min')
        }
        
        // 获取作业ID
        const homeworkId = this.$route.params.id || this.homeworkInfo?.id
        if (!homeworkId) {
          alert('作业ID获取失败')
          return
        }
        
        // 🔥 在提交前回填未修改题目的“上次提交代码与分数”
        await this.ensureMissingQuestionDataFromLastSubmit(homeworkId)
        
        // 计算总分
        let totalScore = 0
        
        logger.log('📊 [HomeworkDetail] ========== 开始计算作业总分 ==========')
        
        // 构建每道题的得分数组，包含代码内容
        const questionScoresArray = this.questions.map((q, index) => {
          const qScore = this.questionScores[q.id] || {}
          const questionScore = parseInt(qScore.score || 0)
          let questionCode = this.questionCodes[q.id] || '' // 获取该题的代码
          
          // 🔥 确保 questionCode 是字符串
          if (typeof questionCode === 'object') {
            logger.warn(`⚠️ [HomeworkDetail] 题目${q.id}的代码是对象，尝试提取code字段`)
            questionCode = questionCode.code || questionCode.codeContent || ''
          }
          
          // 确保 questionCode 是字符串
          questionCode = String(questionCode || '')
          
          totalScore += questionScore
          
          // 详细记录每道题的得分情况
          logger.log(`📝 [HomeworkDetail] 第${index + 1}题 (ID: ${q.id})`)
          logger.log(`  - 题目标题: ${q.title || '未知'}`)
          logger.log(`  - 得分: ${questionScore}`)
          logger.log(`  - 判题类型: ${qScore.isImageComparison ? '图片对比' : '代码判题'}`)
          if (qScore.isImageComparison) {
            logger.log(`  - 图片相似度: ${qScore.similar ? '✅ 相似' : '❌ 不相似'}`)
          }
          if (questionScore === 0 && !qScore.score) {
            logger.warn(`  ⚠️ 该题未进行判题，得分为0`)
          }
          logger.log(`  - 代码类型: ${typeof questionCode}`)
          logger.log(`  - 代码长度: ${questionCode.length} 字符`)
          if (!questionCode || questionCode.length === 0) {
            logger.warn(`  ⚠️ 该题未提交代码`)
          } else {
            logger.log(`  - 代码预览: ${questionCode.substring(0, 50)}...`)
          }
          
          return {
            testQuestionId: String(q.id), // 保持字符串格式，避免大整数精度丢失
            score: questionScore,
            codeContent: questionCode // 每道题的代码内容（确保是字符串）
          }
        })
        
        logger.log('📊 [HomeworkDetail] ========== 统计信息 ==========')
        logger.log('  - 总分:', totalScore)
        logger.log('  - 总耗时(ms):', this.totalElapsedTime)
        logger.log('  - 总耗时(分钟):', (this.totalElapsedTime / 60000).toFixed(2))
        logger.log('  - 题目总数:', this.questions.length)
        logger.log('  - 已判题数:', Object.keys(this.questionScores).length)
        logger.log('  - 已提交代码数:', Object.keys(this.questionCodes).length)
        logger.log('  - 未判题数:', this.questions.length - Object.keys(this.questionScores).length)
        logger.log('  - 平均分:', this.questions.length > 0 ? (totalScore / this.questions.length).toFixed(2) : 0)
        
        // 准备提交数据（根据接口文档）
        // 🔥 homeworkId 保持字符串格式，避免19位大整数精度丢失
        const submitData = {
          homeworkId: String(homeworkId), // 保持字符串格式，确保19位精度不丢失
          totalScore: parseInt(totalScore),
          totalTime: parseInt(this.totalElapsedTime), // 总耗时（毫秒）
          questionScores: questionScoresArray // 包含每道题的得分和代码
        }
        
        logger.log('📋 [HomeworkDetail] ========== 准备提交作业 ==========')
        logger.log('📋 [HomeworkDetail] 提交数据结构:', submitData)
        logger.log('📋 [HomeworkDetail] 作业ID:', submitData.homeworkId)
        logger.log('📋 [HomeworkDetail] 总分:', submitData.totalScore)
        logger.log('📋 [HomeworkDetail] 总耗时(毫秒):', submitData.totalTime)
        logger.log('📋 [HomeworkDetail] 题目得分数组（含代码）:', submitData.questionScores)
        
        // 详细显示每道题的提交数据
        submitData.questionScores.forEach((item, idx) => {
          logger.log(`📝 [HomeworkDetail] 题目${idx + 1} 提交数据:`)
          logger.log(`  - testQuestionId: ${item.testQuestionId}`)
          logger.log(`  - score: ${item.score}`)
          logger.log(`  - codeContent类型: ${typeof item.codeContent}`)
          logger.log(`  - codeContent长度: ${item.codeContent?.length || 0} 字符`)
          if (item.codeContent && typeof item.codeContent === 'string' && item.codeContent.length > 0) {
            logger.log(`  - codeContent预览: ${item.codeContent.substring(0, 50)}...`)
          } else if (!item.codeContent || item.codeContent.length === 0) {
            logger.warn(`  ⚠️ 该题没有代码内容`)
          }
        })
        
        logger.log('📋 [HomeworkDetail] 开始调用API...')
        
        // 调用提交作业API
        const response = await api.post('/goc/homework/submit-result', submitData)
        
        logger.log('✅ [HomeworkDetail] 作业提交成功:', response)
        
        // 停止计时器
        if (this.timerInterval) {
          clearInterval(this.timerInterval)
          this.timerInterval = null
          logger.log('⏱️ [HomeworkDetail] 计时器已停止')
        }
        
        if (response && response.code === 0) {
          logger.log(`✅ [HomeworkDetail] 作业提交成功！总耗时: ${this.displayTime}`)
          
          // 跳转到成绩页面或返回作业列表
          setTimeout(() => {
            this.goBack()
          }, 500)
        } else {
          const errorMsg = response?.message || '提交失败'
          if (this.$message) {
            this.$message.error(errorMsg)
          } else {
            alert(errorMsg)
          }
        }
        
      } catch (error) {
        logger.error('❌ [HomeworkDetail] 提交作业失败:', error)
        
        const errorMessage = error.response?.data?.message || error.message || '提交失败，请重试'
        if (this.$message) {
          this.$message.error(errorMessage)
        } else {
          alert(errorMessage)
        }
      } finally {
        this.isSubmitting = false
      }
    },
    
    // 🔥 自动提交作业（单题判题完成后调用）
    async autoSubmitHomework(questionId) {
      try {
        logger.log('🚀 [HomeworkDetail] 自动提交作业（单题）')
        logger.log('  - 当前题目ID:', questionId)
        
        // 计算总耗时（从进入页面到现在的时间）
        if (this.startTime) {
          this.totalElapsedTime = Date.now() - this.startTime
        }
        
        // 获取作业ID
        const homeworkId = this.$route.params.id || this.homeworkInfo?.id
        if (!homeworkId) {
          logger.error('❌ [HomeworkDetail] 作业ID获取失败，无法自动提交')
          return
        }
        
        // 🔥 回填未修改题目的“上次提交代码与分数”，保证本次自动提交包含所有题数据
        await this.ensureMissingQuestionDataFromLastSubmit(homeworkId)
        
        // 计算总分
        let totalScore = 0
        
        // 构建每道题的得分数组，包含代码内容
        const questionScoresArray = this.questions.map((q, index) => {
          const qScore = this.questionScores[q.id] || {}
          const questionScore = parseInt(qScore.score || 0)
          let questionCode = this.questionCodes[q.id] || ''
          
          // 确保 questionCode 是字符串
          if (typeof questionCode === 'object') {
            questionCode = questionCode.code || questionCode.codeContent || ''
          }
          questionCode = String(questionCode || '')
          
          totalScore += questionScore
          
          return {
            testQuestionId: parseInt(q.id),
            score: questionScore,
            codeContent: questionCode
          }
        })
        
        // 准备提交数据
        // 🔥 homeworkId 保持字符串格式，避免19位大整数精度丢失
        const submitData = {
          homeworkId: String(homeworkId), // 保持字符串格式，确保19位精度不丢失
          totalScore: parseInt(totalScore),
          totalTime: parseInt(this.totalElapsedTime),
          questionScores: questionScoresArray
        }
        
        logger.log('📋 [HomeworkDetail] 自动提交数据:')
        logger.log('  - 作业ID:', submitData.homeworkId)
        logger.log('  - 总分:', submitData.totalScore)
        logger.log('  - 总耗时(毫秒):', submitData.totalTime)
        logger.log('  - 题目数量:', submitData.questionScores.length)
        
        // 调用提交作业API（静默提交，不显示加载状态）
        const response = await api.post('/goc/homework/submit-result', submitData)
        
        logger.log('✅ [HomeworkDetail] 自动提交作业成功:', response)
        
        if (response && response.code === 0) {
          logger.log(`✅ [HomeworkDetail] 作业自动提交成功！当前总分: ${totalScore}`)
        } else {
          const errorMsg = response?.message || '自动提交失败'
          logger.error('❌ [HomeworkDetail] 自动提交失败:', errorMsg)
        }
        
      } catch (error) {
        logger.error('❌ [HomeworkDetail] 自动提交作业失败:', error)
        // 自动提交失败不影响用户继续做题，只记录日志
      }
    },
    
    // 判断是否是图片URL
    isImageUrl(text) {
      if (!text) return false
      
      // 包含图片文件扩展名
      const imageExtensions = ['.jpg', '.jpeg', '.png', '.gif', '.bmp', '.webp']
      const lowerText = text.toLowerCase()
      
      // 检查是否包含图片扩展名
      const hasImageExtension = imageExtensions.some(ext => lowerText.includes(ext))
      
      // 检查是否是URL格式（http开头或包含特殊格式）
      const isUrl = text.startsWith('http') || 
                    text.startsWith('/api/') || 
                    text.includes('文件上传成功')
      
      return hasImageExtension && isUrl
    },
    
    getImageUrl(picturePath) {
      if (!picturePath) return ''
      
      // 🔥 处理后端返回的特殊格式："文件上传成功，文件的url为：[URL]"
      if (picturePath.includes('文件上传成功') && picturePath.includes('url为：')) {
        const urlMatch = picturePath.match(/url为：(.+)$/);
        if (urlMatch && urlMatch[1]) {
          const extractedUrl = urlMatch[1].trim();
          return extractedUrl;
        }
      }
      
      // 如果已经是完整URL，直接返回
      if (picturePath.startsWith('http://') || picturePath.startsWith('https://')) {
        return picturePath
      }
      
      // 拼接完整URL
      // picturePath 已经包含 /api/ 前缀（如：/api/images/xxx.png）
      // 从全局配置中获取正确的 API_BASE_URL
      const GLOBAL_CONFIG = window.GLOBAL_CONFIG || {}
      const baseURL = GLOBAL_CONFIG.API_BASE_URL || 'http://localhost:8000'
      const fullUrl = baseURL + picturePath
      
      return fullUrl
    },
    
    handleImageError(event) {
      logger.warn('⚠️ [HomeworkDetail] 图片加载失败:', event.target.src)
      event.target.style.display = 'none'
      event.target.parentElement.innerHTML += '<p class="image-error">图片加载失败</p>'
    },
    
    formatDate(dateStr) {
      if (!dateStr) return '-'
      try {
        const date = new Date(dateStr)
        if (isNaN(date.getTime())) return dateStr
        return date.toLocaleString('zh-CN', {
          year: 'numeric',
          month: '2-digit',
          day: '2-digit',
          hour: '2-digit',
          minute: '2-digit'
        })
      } catch (error) {
        return dateStr
      }
    },
    
    goBack() {
      // 返回到个人中心的"我的作业"标签页
      this.$router.push({ path: '/profile', query: { tab: 'homework' } })
    },
    
    // 获取题目的详细信息，用于传递给 GocJudge 组件
    // 注意：此函数会在模板渲染时频繁调用，因此移除了日志输出以避免控制台刷屏
    getQuestionWithDetails(question, index) {
      try {
        // 确保 questionDetails 对象存在
        if (!this.questionDetails) {
          this.questionDetails = {}
        }
        
        // 优先使用 questionDetails 中的详细信息，如果没有则使用基础题目信息
        const detailedQuestion = this.questionDetails[index] || question
        
        return detailedQuestion
      } catch (error) {
        // 静默处理错误，避免控制台刷屏
        // 如果发生错误，返回基础题目信息
        return question
      }
    },
    
    // 静默加载题目详情（不显示UI效果）
    async loadQuestionDetailSilently(question, index) {
      try {
        logger.log('🔍 [HomeworkDetail] 静默加载题目详情:', question, index)
        
        // 获取题目ID
        const questionId = question.testQuestionId || question.questionId || question.id
        if (!questionId) {
          logger.warn('⚠️ [HomeworkDetail] 题目ID不存在，无法静默加载详情')
          return
        }
        
        // 动态导入API
        const api = await import('@/api/config')
        
        // 调用接口获取题目详情
        const response = await api.default.get('/goc/testQuestion/findById', {
          params: { id: questionId }
        })
        
        if (response && response.code === 0 && response.data) {
          // 合并题目数据
          const mergedData = {
            ...question,
            ...response.data
          }
          
          // 格式化题目数据
          const detailedQuestion = this.formatQuestion(mergedData)
          
          // 保存题目详细信息
          this.questionDetails[index] = detailedQuestion
          logger.log('✅ [HomeworkDetail] 静默加载完成:', detailedQuestion)
        } else {
          logger.warn('⚠️ [HomeworkDetail] 静默加载失败，响应无效')
        }
      } catch (error) {
        logger.error('❌ [HomeworkDetail] 静默加载失败:', error)
      }
    },
    
    // 🔥 自动加载上次提交的代码到编辑器
    async loadLastSubmitCodeForEditor(question, index) {
      try {
        const homeworkId = this.$route.params.id || this.$route.query.id
        const testQuestionId = question.id || question.testQuestionId || question.questionId
        
        logger.log('📜 [HomeworkDetail] 自动加载上次提交代码到编辑器')
        logger.log('  - 作业ID:', homeworkId)
        logger.log('  - 题目ID:', testQuestionId)
        logger.log('  - 题目索引:', index)
        
        if (!homeworkId || !testQuestionId) {
          logger.warn('⚠️ [HomeworkDetail] 参数不完整，跳过自动加载上次提交')
          return
        }
        
        // 调用API获取上次提交代码
        const response = await homeworkApi.getQuestionCurrentCode(homeworkId, testQuestionId)
        
        logger.log('✅ [HomeworkDetail] 上次提交代码API响应:', response)
        
        // 处理响应数据
        if (response && response.code === 0 && response.data && response.data.codeContent) {
          let lastCode = response.data.codeContent
          // 🔥 同步更新左侧题目导航中的分数（如果返回了分数）
          if (typeof response.data.score !== 'undefined') {
            const qid = question.id || question.testQuestionId || question.questionId
            const scoreVal = parseInt(response.data.score || 0)
            this.questionNavScores[qid] = isNaN(scoreVal) ? 0 : scoreVal
          }
          
          // 🔥 处理特殊字符：换行符、制表符等
          // 后端可能返回转义的字符串，需要还原
          lastCode = lastCode
            .replace(/\\n/g, '\n')   // 处理换行符
            .replace(/\\r/g, '\r')   // 处理回车符
            .replace(/\\t/g, '\t')   // 处理制表符
            .replace(/\\"/g, '"')    // 处理引号
            .replace(/\\'/g, "'")    // 处理单引号
            .replace(/\\\\/g, '\\')  // 处理反斜杠
          
          logger.log('📝 [HomeworkDetail] 上次提交代码加载成功')
          logger.log('  - 原始代码长度:', response.data.codeContent.length)
          logger.log('  - 处理后代码长度:', lastCode.length)
          logger.log('  - 代码预览:', lastCode.substring(0, 100))
          
          // 🔥 将代码保存到题目详情中，GocJudge 组件会使用
          if (!this.questionDetails[index]) {
            this.questionDetails[index] = { ...question }
          }
          
          // 添加初始代码字段
          this.questionDetails[index].initialCode = lastCode
          this.questionDetails[index].starterCode = lastCode
          
          // 🔥 强制更新 questions 数组，触发 GocJudge 组件的 watch
          this.questions[index] = {
            ...this.questions[index],
            starterCode: lastCode,
            initialCode: lastCode
          }
          
          logger.log('✅ [HomeworkDetail] 上次提交的代码已设置为编辑器初始代码')
          
          // 🔥 强制刷新视图，确保 GocJudge 组件接收到新数据
          this.$nextTick(() => {
            this.$forceUpdate()
          })
        } else {
          logger.log('ℹ️ [HomeworkDetail] 无上次提交代码，使用默认模板')
        }
        
      } catch (error) {
        logger.error('❌ [HomeworkDetail] 自动加载上次提交代码失败:', error)
        // 失败时不影响编辑器打开，使用默认代码
      }
    },
    
    // 🔥 在提交前：为没有本次修改痕迹的题目回填“上次提交的代码与分数”
    async ensureMissingQuestionDataFromLastSubmit(homeworkId) {
      try {
        if (!this.questions || this.questions.length === 0) return
        
        const tasks = this.questions.map(async (q, idx) => {
          const qid = q.id || q.testQuestionId || q.questionId
          if (!qid) return
          
          const hasCode = !!this.questionCodes[qid]
          const hasScore = !!(this.questionScores[qid] && (this.questionScores[qid].score || this.questionScores[qid].score === 0))
          
          // 仅当缺代码或缺分数时才拉取历史
          if (!hasCode || !hasScore) {
            try {
              const resp = await homeworkApi.getQuestionCurrentCode(homeworkId, qid)
              if (resp && resp.code === 0 && resp.data) {
                // 回填代码
                if (!hasCode && resp.data.codeContent) {
                  let lastCode = resp.data.codeContent
                  lastCode = lastCode
                    .replace(/\\n/g, '\n')
                    .replace(/\\r/g, '\r')
                    .replace(/\\t/g, '\t')
                    .replace(/\\"/g, '"')
                    .replace(/\\'/g, "'")
                    .replace(/\\\\/g, '\\')
                  this.questionCodes[qid] = String(lastCode || '')
                }
                // 回填分数
                if (!hasScore && (resp.data.score || resp.data.score === 0)) {
                  const scoreVal = parseInt(resp.data.score || 0)
                  this.questionScores[qid] = {
                    ...(this.questionScores[qid] || {}),
                    score: isNaN(scoreVal) ? 0 : scoreVal
                  }
                }
              }
            } catch (e) {
              logger.warn('⚠️ [HomeworkDetail] 回填题目历史数据失败:', { qid, error: e })
            }
          }
        })
        
        await Promise.all(tasks)
        logger.log('✅ [HomeworkDetail] 未修改题目历史代码与分数回填完成')
      } catch (error) {
        logger.warn('⚠️ [HomeworkDetail] 回填历史数据过程中出现问题:', error)
      }
    },
    
    // 🔥 显示自动关闭的消息提示（1秒后自动关闭）
    showAutoCloseMessage(message) {
      const messageEl = document.createElement('div')
      messageEl.className = 'auto-close-message'
      messageEl.textContent = message
      messageEl.style.cssText = `
        position: fixed;
        top: 20px;
        left: 50%;
        transform: translateX(-50%);
        background: #67C23A;
        color: white;
        padding: 12px 24px;
        border-radius: 6px;
        box-shadow: 0 4px 12px rgba(103, 194, 58, 0.4);
        z-index: 10000;
        font-size: 14px;
        font-weight: 500;
        animation: slideDown 0.3s ease-out;
      `
      
      document.body.appendChild(messageEl)
      
      // 1秒后自动移除
      setTimeout(() => {
        messageEl.style.animation = 'slideUp 0.3s ease-out'
        setTimeout(() => {
          document.body.removeChild(messageEl)
        }, 300)
      }, 1000)
    }
  }
}
</script>

<style scoped>
/* 自动关闭消息提示动画 */
@keyframes slideDown {
  from {
    opacity: 0;
    transform: translateX(-50%) translateY(-20px);
  }
  to {
    opacity: 1;
    transform: translateX(-50%) translateY(0);
  }
}

@keyframes slideUp {
  from {
    opacity: 1;
    transform: translateX(-50%) translateY(0);
  }
  to {
    opacity: 0;
    transform: translateX(-50%) translateY(-20px);
  }
}

/* 弹窗遮罩层 - 现代精美版 */
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: linear-gradient(135deg, rgba(102, 126, 234, 0.25) 0%, rgba(118, 75, 162, 0.25) 100%),
              rgba(0, 0, 0, 0.6);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 9999;
  padding: 20px;
  backdrop-filter: blur(8px);
  animation: fadeIn 0.35s cubic-bezier(0.4, 0, 0.2, 1);
}

@keyframes fadeIn {
  from {
    opacity: 0;
    backdrop-filter: blur(0px);
  }
  to {
    opacity: 1;
    backdrop-filter: blur(8px);
  }
}

/* 弹窗容器基础样式 */
.modal-container {
  background: white;
  border-radius: 16px;
  box-shadow: 0 20px 60px rgba(0, 0, 0, 0.3);
  max-width: 90%;
  max-height: 90vh;
  overflow: hidden;
  display: flex;
  flex-direction: column;
  animation: slideUp 0.3s ease-out;
}

@keyframes slideUp {
  from {
    opacity: 0;
    transform: translateY(30px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

/* 弹窗头部 - 现代精美版 */
.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 28px 40px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  border-bottom: none;
  position: relative;
  overflow: hidden;
  box-shadow: 0 4px 20px rgba(102, 126, 234, 0.3);
}

.modal-header::before {
  content: '';
  position: absolute;
  top: -50%;
  right: -20%;
  width: 400px;
  height: 400px;
  background: radial-gradient(circle, rgba(255, 255, 255, 0.12) 0%, transparent 70%);
  border-radius: 50%;
  pointer-events: none;
}

.modal-title-section {
  display: flex;
  align-items: center;
  gap: 16px;
  position: relative;
  z-index: 1;
}

.modal-title-section i {
  font-size: 28px;
  color: rgba(255, 255, 255, 0.95);
  filter: drop-shadow(0 3px 6px rgba(0, 0, 0, 0.2));
}

.modal-title-section h3 {
  margin: 0;
  font-size: 24px;
  font-weight: 700;
  letter-spacing: 0.5px;
  text-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
}

.modal-close-btn {
  background: rgba(255, 255, 255, 0.15);
  border: 2px solid rgba(255, 255, 255, 0.25);
  color: white;
  width: 44px;
  height: 44px;
  border-radius: 50%;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.35s cubic-bezier(0.4, 0, 0.2, 1);
  font-size: 18px;
  position: relative;
  z-index: 1;
  backdrop-filter: blur(8px);
}

.modal-close-btn:hover {
  background: rgba(255, 255, 255, 0.25);
  border-color: rgba(255, 255, 255, 0.4);
  transform: rotate(90deg) scale(1.08);
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.2);
}

.modal-close-btn:active {
  transform: rotate(90deg) scale(0.95);
}

.modal-close-btn i {
  font-size: 20px;
}

/* 弹窗主体 */
.modal-body {
  flex: 1;
  overflow-y: auto;
  background: #f8f9fc;
}

.modal-body::-webkit-scrollbar {
  width: 10px;
}

.modal-body::-webkit-scrollbar-track {
  background: #f1f1f1;
}

.modal-body::-webkit-scrollbar-thumb {
  background: #888;
  border-radius: 5px;
}

.modal-body::-webkit-scrollbar-thumb:hover {
  background: #555;
}

/* 弹窗底部 - 现代精美版 */
.modal-footer {
  display: flex;
  justify-content: flex-end;
  gap: 15px;
  padding: 25px 40px;
  background: linear-gradient(to top, #fafbfc, #ffffff);
  border-top: 1px solid #e9ecef;
  box-shadow: 0 -4px 16px rgba(0, 0, 0, 0.04);
}

.modal-btn {
  padding: 12px 32px;
  border: none;
  border-radius: 10px;
  font-size: 15px;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  letter-spacing: 0.3px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
}

.modal-btn.primary {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
}

.modal-btn.primary:hover {
  transform: translateY(-3px);
  box-shadow: 0 6px 20px rgba(102, 126, 234, 0.4);
}

.modal-btn.primary:active {
  transform: translateY(-1px);
  box-shadow: 0 3px 12px rgba(102, 126, 234, 0.35);
}

.modal-btn.secondary {
  background: linear-gradient(135deg, #6c757d 0%, #5a6268 100%);
  color: white;
}

.modal-btn.secondary:hover {
  transform: translateY(-3px);
  box-shadow: 0 6px 20px rgba(108, 117, 125, 0.4);
}

.modal-btn.secondary:active {
  transform: translateY(-1px);
  box-shadow: 0 3px 12px rgba(108, 117, 125, 0.35);
}

.homework-detail-page {
  min-height: 100vh;
  background: #f5f7fa;
  padding: 10px;
  max-width: 100%;
}

.back-button {
  margin-bottom: 20px;
}

.btn-back {
  padding: 10px 20px;
  background: #3498db;
  color: white;
  border: none;
  border-radius: 6px;
  cursor: pointer;
  font-size: 14px;
  transition: background 0.3s;
}

.btn-back:hover {
  background: #2980b9;
}

.homework-info-card {
  background: white;
  border-radius: 12px;
  padding: 30px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  margin-bottom: 30px;
}

.homework-title {
  font-size: 28px;
  color: #2c3e50;
  margin: 0 0 20px 0;
  font-weight: 600;
}

.homework-meta {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
  gap: 15px;
  margin-bottom: 20px;
}

.meta-item {
  display: flex;
  align-items: center;
}

.meta-item .label {
  font-weight: 600;
  color: #666;
}

.meta-item .value {
  color: #333;
  margin-left: 5px;
}

.timer-item {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  padding: 10px 15px;
  border-radius: 8px;
  color: white !important;
}

.timer-item .label {
  color: rgba(255, 255, 255, 0.9) !important;
  font-weight: 600;
}

.timer-value {
  font-family: 'Courier New', monospace;
  font-size: 18px;
  font-weight: bold;
  color: #fff !important;
  background: rgba(0, 0, 0, 0.2);
  padding: 4px 12px;
  border-radius: 4px;
  margin-left: 10px !important;
}

.meta-item .label {
  font-weight: 600;
  color: #666;
  margin-right: 10px;
}

.meta-item .value {
  color: #333;
}

.homework-description {
  margin-top: 20px;
  padding-top: 20px;
  border-top: 1px solid #eee;
}

.homework-description h3 {
  font-size: 18px;
  color: #2c3e50;
  margin: 0 0 10px 0;
}

.homework-description p {
  color: #666;
  line-height: 1.6;
  white-space: pre-wrap;
}

.questions-section {
  background: white;
  border-radius: 12px;
  padding: 30px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.section-title {
  font-size: 24px;
  color: #2c3e50;
  margin: 0 0 25px 0;
  font-weight: 600;
  padding-bottom: 15px;
  border-bottom: 3px solid linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

.questions-layout {
  display: flex;
  gap: 24px;
}

.question-nav {
  width: 220px;
  flex-shrink: 0;
  background: #f6f8ff;
  border-radius: 14px;
  border: 1px solid rgba(102, 126, 234, 0.2);
  padding: 20px 18px;
  box-shadow: 0 8px 20px rgba(102, 126, 234, 0.1);
  position: sticky;
  top: 120px;
  align-self: flex-start;
}

.nav-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.nav-title {
  font-size: 16px;
  font-weight: 600;
  color: #2c3e50;
}

.nav-count {
  font-size: 12px;
  color: #667eea;
  background: rgba(102, 126, 234, 0.15);
  padding: 4px 10px;
  border-radius: 999px;
  font-weight: 500;
}

.question-nav-list {
  list-style: none;
  padding: 0;
  margin: 0;
  display: grid;
  grid-template-columns: repeat(5, 1fr);
  gap: 4px;
  justify-items: center;
  align-items: center;
}

.question-nav-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  gap: 2px;
  padding: 0;
  border-radius: 0;
  cursor: pointer;
  transition: all 0.25s ease;
  background: transparent;
  border: none;
  box-shadow: none;
}

.question-nav-item:hover {
  transform: none;
}

.question-nav-item.active {
  color: #fff;
}

.question-nav-item.active .item-index {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: #fff;
  border-color: transparent;
  box-shadow: 0 4px 10px rgba(102, 126, 234, 0.25);
}

.item-index {
  width: 34px;
  height: 34px;
  border-radius: 6px;
  background: #fff;
  color: #667eea;
  display: flex;
  align-items: center;
  justify-content: center;
  font-weight: 700;
  font-size: 14px;
  border: 1px dashed rgba(102, 126, 234, 0.45);
}

.item-score-below {
  font-size: 12px;
  font-weight: 700;
  color: #3c4fe0;
  line-height: 1;
}

.questions-list {
  display: flex;
  flex-direction: column;
  gap: 20px;
  flex: 1;
  min-width: 0;
}

@media (max-width: 1200px) {
  .question-nav {
    width: 220px;
  }
}

@media (max-width: 1024px) {
  .questions-layout {
    flex-direction: column;
  }

  .question-nav {
    width: 100%;
    position: static;
    box-shadow: none;
  }
}

@media (max-width: 768px) {
  .question-nav-list {
    grid-template-columns: repeat(5, 1fr);
    gap: 8px;
  }
}

@media (max-width: 576px) {
  .question-nav-list {
    grid-template-columns: repeat(5, 1fr);
    gap: 6px;
  }
}

.question-card {
  background: #fafafa;
  border-radius: 12px;
  padding: 25px;
  border: 2px solid #e0e0e0;
  transition: all 0.3s;
}

.question-card:hover {
  border-color: #667eea;
  box-shadow: 0 4px 12px rgba(102, 126, 234, 0.15);
}

.question-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.header-left {
  display: flex;
  align-items: center;
  gap: 12px;
}

.question-number {
  font-size: 16px;
  font-weight: 600;
  color: #667eea;
  background: #f0f2ff;
  padding: 6px 16px;
  border-radius: 20px;
}

.view-detail-btn {
  padding: 8px 20px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  border: none;
  border-radius: 20px;
  font-size: 14px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.3s;
  box-shadow: 0 2px 8px rgba(102, 126, 234, 0.3);
}

.view-detail-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(102, 126, 234, 0.5);
}

.view-detail-btn:active {
  transform: translateY(0);
}

.question-difficulty {
  padding: 6px 16px;
  border-radius: 20px;
  font-size: 14px;
  font-weight: 600;
}

.difficulty-easy {
  background: #e8f5e9;
  color: #388e3c;
}

.difficulty-medium {
  background: #fff3e0;
  color: #f57c00;
}

.difficulty-hard {
  background: #ffebee;
  color: #d32f2f;
}

.question-title {
  font-size: 20px;
  color: #2c3e50;
  margin: 0 0 15px 0;
  font-weight: 600;
}

.question-info {
  display: flex;
  gap: 20px;
  margin-bottom: 20px;
  flex-wrap: wrap;
}

.info-item {
  display: flex;
  align-items: center;
  font-size: 14px;
}

.info-item .label {
  color: #666;
  margin-right: 5px;
}

.info-item .value {
  color: #333;
  font-weight: 600;
}

.question-description,
.question-format {
  margin-top: 20px;
  padding: 20px;
  background: white;
  border-radius: 8px;
  border-left: 4px solid #667eea;
}

.question-description h4,
.question-format h4 {
  margin: 0 0 10px 0;
  color: #2c3e50;
  font-size: 16px;
  font-weight: 600;
}

.question-description p,
.question-format p {
  margin: 0;
  color: #666;
  line-height: 1.6;
  white-space: pre-wrap;
}

.question-image {
  margin-top: 20px;
  padding: 20px;
  background: white;
  border-radius: 8px;
  border-left: 4px solid #667eea;
}

.question-image h4 {
  margin: 0 0 15px 0;
  color: #2c3e50;
  font-size: 16px;
  font-weight: 600;
}

.question-image img {
  max-width: 400px;
  max-height: 300px;
  height: auto;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  display: block;
  margin: 0 auto;
}

.image-error {
  color: #f56c6c;
  font-size: 14px;
  padding: 10px;
  background: #fef0f0;
  border-radius: 4px;
}

/* 测试用例样式 */
.question-test-cases {
  margin-top: 20px;
  padding: 20px;
  background: white;
  border-radius: 8px;
  border-left: 4px solid #667eea;
}

.question-test-cases h4 {
  margin: 0 0 15px 0;
  color: #2c3e50;
  font-size: 16px;
  font-weight: 600;
}

.test-cases-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(400px, 1fr));
  gap: 20px;
}

.test-case-card {
  border: 2px solid #e9ecef;
  border-radius: 12px;
  overflow: hidden;
  background: white;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  transition: all 0.3s ease;
}

.test-case-card:hover {
  border-color: #667eea;
  box-shadow: 0 4px 15px rgba(102, 126, 234, 0.1);
  transform: translateY(-2px);
}

.test-case-header-small {
  background: linear-gradient(135deg, #667eea, #764ba2);
  color: white;
  padding: 12px 18px;
  text-align: center;
  font-weight: 600;
  font-size: 15px;
}

.test-case-body {
  padding: 20px;
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.test-case-field {
  display: flex;
  flex-direction: column;
  gap: 6px;
}

.test-case-field label {
  font-size: 14px;
  font-weight: 600;
  color: #495057;
  letter-spacing: 0.3px;
}

.test-case-field .field-content {
  background: #f8f9fa;
  padding: 15px 18px;
  border-radius: 8px;
  border: 2px solid #e9ecef;
  font-family: 'Courier New', monospace;
  font-size: 16px;
  color: #2c3e50;
  white-space: pre-wrap;
  word-break: break-word;
  line-height: 1.8;
  min-height: 60px;
}

.test-case-field .field-image {
  text-align: center;
  padding: 15px;
  background: #f8f9fa;
  border-radius: 8px;
  border: 2px solid #e9ecef;
}

.test-case-field .field-image img {
  max-width: 100%;
  max-height: 350px;
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
  transition: transform 0.3s ease;
}

.test-case-field .field-image img:hover {
  transform: scale(1.05);
  cursor: zoom-in;
  box-shadow: 0 6px 20px rgba(0, 0, 0, 0.25);
}

.question-code,
.question-reference-code {
  margin-top: 20px;
  background: white;
  border-radius: 8px;
  overflow: hidden;
}

.question-code h4 {
  margin: 0;
  padding: 12px 20px;
  background: #2c3e50;
  color: white;
  font-size: 14px;
  font-weight: 600;
}

.question-reference-code .reference-code-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 20px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

.question-reference-code h4 {
  margin: 0;
  color: white;
  font-size: 14px;
  font-weight: 600;
}

.reference-code-actions {
  display: flex;
  gap: 10px;
  align-items: center;
}

.last-submit-btn {
  padding: 8px 16px;
  background: rgba(255, 255, 255, 0.2);
  color: white;
  border: 1px solid rgba(255, 255, 255, 0.3);
  border-radius: 6px;
  cursor: pointer;
  font-size: 14px;
  font-weight: 500;
  display: inline-flex;
  align-items: center;
  gap: 6px;
  transition: all 0.3s ease;
}

.last-submit-btn:hover {
  background: rgba(255, 255, 255, 0.3);
  border-color: rgba(255, 255, 255, 0.5);
  transform: translateY(-2px);
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
}

.last-submit-btn i {
  font-size: 14px;
}

.toggle-code-btn {
  padding: 6px 16px;
  background: rgba(255, 255, 255, 0.2);
  color: white;
  border: 1px solid rgba(255, 255, 255, 0.3);
  border-radius: 20px;
  font-size: 13px;
  cursor: pointer;
  transition: all 0.3s;
  font-weight: 500;
}

.toggle-code-btn:hover {
  background: rgba(255, 255, 255, 0.3);
  border-color: rgba(255, 255, 255, 0.5);
  transform: translateY(-1px);
}

.toggle-code-btn:active {
  transform: translateY(0);
}

.code-hidden-hint {
  padding: 40px 20px;
  text-align: center;
  background: #f5f5f5;
  color: #999;
}

.code-hidden-hint i {
  font-size: 32px;
  margin-bottom: 10px;
  display: block;
  color: #ccc;
}

.code-hidden-hint p {
  margin: 0;
  font-size: 14px;
}

/* 上次提交代码弹窗样式 - 现代精美版 */
.last-submit-modal {
  max-width: 1500px;
  width: 96%;
  max-height: 95vh;
  overflow: hidden;
  border-radius: 24px;
  box-shadow: 0 25px 80px rgba(0, 0, 0, 0.35);
  background: #ffffff;
  display: flex;
  flex-direction: column;
}

.last-submit-content {
  padding: 0;
  background: #f5f7fa;
  flex: 1;
  overflow-y: auto;
}

.last-submit-content::-webkit-scrollbar {
  width: 10px;
}

.last-submit-content::-webkit-scrollbar-track {
  background: #e9ecef;
}

.last-submit-content::-webkit-scrollbar-thumb {
  background: linear-gradient(180deg, #667eea, #764ba2);
  border-radius: 5px;
}

.last-submit-content::-webkit-scrollbar-thumb:hover {
  background: linear-gradient(180deg, #5568d3, #6a3f8f);
}

.submit-info-section {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  padding: 45px 55px;
  margin: 0;
  border-radius: 0;
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
  gap: 45px;
  box-shadow: 0 8px 32px rgba(102, 126, 234, 0.4);
  position: relative;
  overflow: hidden;
}

.submit-info-section::before {
  content: '';
  position: absolute;
  top: -50%;
  right: -10%;
  width: 500px;
  height: 500px;
  background: radial-gradient(circle, rgba(255, 255, 255, 0.1) 0%, transparent 70%);
  border-radius: 50%;
  pointer-events: none;
}

.submit-info-section::after {
  content: '';
  position: absolute;
  bottom: -30%;
  left: -5%;
  width: 400px;
  height: 400px;
  background: radial-gradient(circle, rgba(255, 255, 255, 0.08) 0%, transparent 70%);
  border-radius: 50%;
  pointer-events: none;
}

.submit-info-section .info-item {
  display: flex;
  flex-direction: column;
  gap: 14px;
  position: relative;
  z-index: 1;
  padding: 24px;
  background: rgba(255, 255, 255, 0.1);
  border-radius: 16px;
  backdrop-filter: blur(10px);
  border: 1px solid rgba(255, 255, 255, 0.2);
  transition: all 0.3s ease;
}

.submit-info-section .info-item:hover {
  background: rgba(255, 255, 255, 0.15);
  transform: translateY(-4px);
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.2);
}

.submit-info-section .label {
  font-size: 13px;
  color: rgba(255, 255, 255, 0.85);
  font-weight: 600;
  letter-spacing: 1.2px;
  text-transform: uppercase;
  display: flex;
  align-items: center;
  gap: 8px;
}

.submit-info-section .value {
  font-size: 28px;
  color: white;
  font-weight: 900;
  text-shadow: 0 4px 8px rgba(0, 0, 0, 0.25);
  letter-spacing: 0.5px;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', system-ui, sans-serif;
}

.code-display-section {
  background: white;
  border-radius: 0;
  overflow: hidden;
  box-shadow: none;
  margin: 30px 35px 35px 35px;
  border-radius: 20px;
  border: 1px solid #e9ecef;
}

.code-display-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 28px 40px;
  background: linear-gradient(135deg, #2c3e50 0%, #34495e 100%);
  color: white;
  box-shadow: 0 4px 20px rgba(44, 62, 80, 0.2);
  border-bottom: 3px solid #3498db;
}

.code-display-header h4 {
  margin: 0;
  font-size: 20px;
  font-weight: 700;
  display: flex;
  align-items: center;
  gap: 14px;
  letter-spacing: 0.5px;
}

.code-display-header h4 i {
  font-size: 22px;
  color: #3498db;
}

.copy-btn-large {
  padding: 12px 32px;
  background: #3498db;
  color: white;
  border: none;
  border-radius: 10px;
  cursor: pointer;
  font-size: 15px;
  font-weight: 600;
  transition: all 0.3s ease;
  display: inline-flex;
  align-items: center;
  gap: 10px;
  white-space: nowrap;
  letter-spacing: 0.3px;
  box-shadow: 0 4px 12px rgba(52, 152, 219, 0.3);
}

.copy-btn-large:hover {
  background: #2980b9;
  transform: translateY(-3px);
  box-shadow: 0 8px 20px rgba(52, 152, 219, 0.45);
}

.copy-btn-large:active {
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(52, 152, 219, 0.35);
}

.copy-btn-large i {
  font-size: 15px;
}

.large-code-block {
  margin: 0;
  padding: 50px 45px;
  background: linear-gradient(to bottom, #1e1e1e 0%, #252525 100%);
  color: #d4d4d4;
  overflow-x: auto;
  font-family: 'Consolas', 'Monaco', 'Courier New', 'Fira Code', monospace;
  font-size: 17px;
  line-height: 2.6;
  box-shadow: inset 0 8px 24px rgba(0, 0, 0, 0.6);
  border: none;
  min-height: 550px;
  max-height: 700px;
  overflow-y: auto;
  position: relative;
}

.large-code-block::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  height: 40px;
  background: linear-gradient(to bottom, rgba(0, 0, 0, 0.3), transparent);
  pointer-events: none;
}

.large-code-block::-webkit-scrollbar {
  width: 14px;
  height: 14px;
}

.large-code-block::-webkit-scrollbar-track {
  background: #1a1a1a;
  border-radius: 7px;
  border: 2px solid #252525;
}

.large-code-block::-webkit-scrollbar-thumb {
  background: linear-gradient(180deg, #3498db, #2980b9);
  border-radius: 7px;
  transition: background 0.3s ease;
  border: 2px solid #252525;
}

.large-code-block::-webkit-scrollbar-thumb:hover {
  background: linear-gradient(180deg, #5dade2, #3498db);
}

.large-code-block::-webkit-scrollbar-corner {
  background: #1a1a1a;
}

.large-code-block code {
  white-space: pre;
  display: block;
  color: #e06c75;
  text-shadow: 0 2px 4px rgba(0, 0, 0, 0.4);
  font-weight: 500;
}

/* 上次提交代码弹窗响应式 - 优化版 */
@media (max-width: 768px) {
  .last-submit-modal {
    max-width: 96%;
    width: 96%;
    border-radius: 20px;
    max-height: 92vh;
  }
  
  .modal-header {
    padding: 20px 24px;
  }
  
  .modal-title-section h3 {
    font-size: 19px;
  }
  
  .modal-title-section i {
    font-size: 22px;
  }
  
  .modal-close-btn {
    width: 38px;
    height: 38px;
  }
  
  .last-submit-content {
    padding: 0;
  }
  
  .submit-info-section {
    grid-template-columns: 1fr;
    padding: 32px 24px;
    gap: 20px;
  }
  
  .submit-info-section .info-item {
    padding: 20px;
  }
  
  .submit-info-section .value {
    font-size: 24px;
  }
  
  .code-display-section {
    margin: 20px 20px 24px 20px;
    border-radius: 16px;
  }
  
  .code-display-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 16px;
    padding: 20px 24px;
  }
  
  .code-display-header h4 {
    font-size: 17px;
  }
  
  .copy-btn-large {
    width: 100%;
    justify-content: center;
    padding: 12px 20px;
  }
  
  .large-code-block {
    padding: 30px 20px;
    font-size: 15px;
    line-height: 2.4;
    min-height: 400px;
    max-height: 500px;
  }
  
  .modal-footer {
    padding: 20px 24px;
    gap: 12px;
  }
  
  .modal-btn {
    padding: 12px 24px;
    font-size: 14px;
  }
}

.question-editor-section {
  margin-top: 20px;
  background: white;
  border-radius: 8px;
  overflow: hidden;
  border: 2px solid #e0e0e0;
}

.editor-toggle-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 20px;
  background: linear-gradient(135deg, #42b983 0%, #35a372 100%);
}

.editor-toggle-header h4 {
  margin: 0;
  color: white;
  font-size: 14px;
  font-weight: 600;
}

.toggle-editor-btn {
  padding: 6px 16px;
  background: rgba(255, 255, 255, 0.2);
  color: white;
  border: 1px solid rgba(255, 255, 255, 0.3);
  border-radius: 20px;
  font-size: 13px;
  cursor: pointer;
  transition: all 0.3s;
  font-weight: 500;
}

.toggle-editor-btn:hover {
  background: rgba(255, 255, 255, 0.3);
  border-color: rgba(255, 255, 255, 0.5);
  transform: translateY(-1px);
}

.toggle-editor-btn:active {
  transform: translateY(0);
}

.question-editor-section .editor-container {
  padding: 0;
  background: #f5f5f5;
  min-height: 80vh;
  width: 100%;
}

/* 提交作业按钮区域 */
.submit-homework-section {
  padding: 30px;
  background: linear-gradient(to bottom, #f8f9fa, #ffffff);
  border-top: 3px solid #e0e0e0;
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 20px;
  margin-top: 30px;
  border-radius: 8px;
  box-shadow: 0 -4px 12px rgba(0, 0, 0, 0.05);
  flex-wrap: wrap;
}

/* 查看提交按钮 */
.btn-view-submission {
  padding: 14px 32px;
  background: linear-gradient(135deg, #3498db 0%, #2980b9 100%);
  color: white;
  border: none;
  border-radius: 8px;
  font-size: 16px;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s ease;
  box-shadow: 0 4px 12px rgba(52, 152, 219, 0.3);
  display: inline-flex;
  align-items: center;
  gap: 8px;
}

.btn-view-submission:hover {
  background: linear-gradient(135deg, #2980b9 0%, #21618c 100%);
  transform: translateY(-2px);
  box-shadow: 0 6px 16px rgba(52, 152, 219, 0.4);
}

.btn-view-submission:active {
  transform: translateY(0);
  box-shadow: 0 4px 12px rgba(52, 152, 219, 0.3);
}

.btn-view-submission i {
  font-size: 16px;
}

.btn-submit-homework {
  padding: 12px 40px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  border: none;
  border-radius: 8px;
  font-size: 16px;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s;
  box-shadow: 0 4px 15px rgba(102, 126, 234, 0.4);
}

.btn-submit-homework:hover:not(:disabled) {
  transform: translateY(-2px);
  box-shadow: 0 6px 20px rgba(102, 126, 234, 0.6);
}

.btn-submit-homework:active:not(:disabled) {
  transform: translateY(0);
}

.btn-submit-homework:disabled {
  opacity: 0.6;
  cursor: not-allowed;
  transform: none;
}

.btn-submit-homework.expired {
  background: linear-gradient(135deg, #6c757d, #5a6268);
  box-shadow: 0 4px 15px rgba(108, 117, 125, 0.4);
  cursor: not-allowed;
}

.btn-submit-homework.expired:hover {
  transform: none;
  box-shadow: 0 4px 15px rgba(108, 117, 125, 0.4);
}

.expired-hint {
  margin: 10px 0 0 0;
  font-size: 14px;
  color: #e74c3c;
  font-weight: 600;
  text-align: center;
}

/* 题目描述图片样式 */
.question-description-image {
  margin-top: 20px;
  padding: 20px;
  background: white;
  border-radius: 8px;
  border-left: 4px solid #667eea;
}

.question-description-image h4 {
  margin: 0 0 15px 0;
  color: #2c3e50;
  font-size: 16px;
  font-weight: 600;
}

.question-description-image img {
  max-width: 500px;
  max-height: 400px;
  height: auto;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  display: block;
  margin: 0 auto;
  transition: transform 0.3s ease, box-shadow 0.3s ease;
}

.question-description-image img:hover {
  transform: scale(1.02);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
  cursor: zoom-in;
}

/* 输出格式图片样式 */
.output-image-container {
  margin-top: 15px;
  text-align: center;
  padding: 15px;
  background: white;
  border-radius: 8px;
}

.output-format-image {
  max-width: 400px;
  height: auto;
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
  border: 1px solid #e1e4e8;
  transition: transform 0.3s ease, box-shadow 0.3s ease;
}

.output-format-image:hover {
  transform: scale(1.02);
  box-shadow: 0 6px 20px rgba(0, 0, 0, 0.2);
  cursor: zoom-in;
}

.output-image-container .image-caption {
  margin-top: 10px;
  font-size: 14px;
  color: #666;
  font-style: italic;
}

.question-code pre,
.question-reference-code pre {
  margin: 0;
  padding: 20px;
  background: #1e1e1e;
  overflow-x: auto;
  white-space: pre;
}

.question-code code,
.question-reference-code code {
  color: #d4d4d4;
  font-family: 'Consolas', 'Monaco', 'Courier New', monospace;
  font-size: 13px;
  line-height: 1.6;
  white-space: inherit;
}

.question-testcases {
  margin-top: 20px;
}

.question-testcases h4 {
  margin: 0 0 15px 0;
  color: #2c3e50;
  font-size: 16px;
}

.testcase-item {
  background: white;
  border-radius: 8px;
  margin-bottom: 12px;
  overflow: hidden;
  border: 1px solid #e0e0e0;
}

.testcase-header {
  padding: 10px 15px;
  background: #f5f5f5;
  font-weight: 600;
  color: #555;
  font-size: 14px;
}

.testcase-content {
  padding: 15px;
}

.testcase-field {
  margin-bottom: 10px;
  font-size: 14px;
  color: #666;
  line-height: 1.6;
}

.testcase-field:last-child {
  margin-bottom: 0;
}

.testcase-field strong {
  color: #333;
  margin-right: 8px;
}

.no-questions {
  background: white;
  border-radius: 12px;
  padding: 60px 20px;
  text-align: center;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.no-questions p {
  font-size: 16px;
  color: #999;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .homework-detail-page {
    padding: 10px;
  }

  .homework-info-card {
    padding: 20px;
  }

  .homework-title {
    font-size: 22px;
  }

  .homework-meta {
    grid-template-columns: 1fr;
  }

  .question-card {
    padding: 15px;
  }

  .question-title {
    font-size: 18px;
  }

  .question-info {
    flex-direction: column;
    gap: 10px;
  }

  .question-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 12px;
  }

  .header-left {
    width: 100%;
    justify-content: space-between;
  }

  .view-detail-btn {
    width: 100%;
  }

  .reference-code-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }

  .reference-code-actions {
    width: 100%;
    flex-direction: column;
  }

  .last-submit-btn,
  .toggle-code-btn {
    width: 100%;
    padding: 8px 16px;
    justify-content: center;
  }

  .editor-toggle-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }

  .toggle-editor-btn {
    width: 100%;
    padding: 8px 16px;
  }
  
  .test-cases-grid {
    grid-template-columns: 1fr;
  }
  
  .test-case-card {
    margin-bottom: 10px;
  }
}

/* 提交代码弹窗样式 */
.submission-modal {
  max-width: 900px;
  max-height: 90vh;
  overflow-y: auto;
}

.loading-section {
  padding: 80px 40px;
  text-align: center;
  color: #667eea;
  background: linear-gradient(135deg, #f8f9fc 0%, #fff 100%);
}

.loading-section i {
  font-size: 48px;
  margin-bottom: 20px;
  display: block;
  color: #667eea;
  animation: spin 1.2s linear infinite;
}

@keyframes spin {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}

.loading-section p {
  font-size: 16px;
  font-weight: 500;
  color: #6c757d;
  margin: 0;
  letter-spacing: 0.3px;
}

.submission-content {
  padding: 20px;
}

.submission-info-section {
  background: linear-gradient(135deg, #f5f7fa 0%, #e8ecf1 100%);
  padding: 20px;
  border-radius: 8px;
  margin-bottom: 24px;
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 16px;
}

.submission-info-section .info-item {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.submission-info-section .label {
  font-size: 13px;
  color: #666;
  font-weight: 500;
}

.submission-info-section .value {
  font-size: 15px;
  color: #333;
  font-weight: 600;
}

.score-highlight {
  color: #3498db;
  font-size: 18px;
}

.questions-code-section {
  margin-top: 24px;
}

.questions-code-section .section-title {
  font-size: 16px;
  color: #333;
  margin-bottom: 16px;
  padding-bottom: 8px;
  border-bottom: 2px solid #e0e0e0;
}

.question-code-card {
  background: white;
  border: 2px solid #e9ecef;
  border-radius: 8px;
  margin-bottom: 20px;
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.code-card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 20px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
}

.code-card-header .header-left {
  display: flex;
  align-items: center;
  gap: 12px;
}

.question-number {
  font-weight: 600;
  font-size: 14px;
  background: rgba(255, 255, 255, 0.2);
  padding: 4px 12px;
  border-radius: 12px;
}

.question-name {
  font-size: 15px;
  font-weight: 500;
}

.score-badge {
  padding: 6px 16px;
  border-radius: 16px;
  font-weight: 600;
  font-size: 14px;
}

.score-badge.score-excellent {
  background: #d4edda;
  color: #155724;
}

.score-badge.score-good {
  background: #d1ecf1;
  color: #0c5460;
}

.score-badge.score-pass {
  background: #fff3cd;
  color: #856404;
}

.score-badge.score-fail {
  background: #f8d7da;
  color: #721c24;
}

.score-badge.score-zero {
  background: #e2e3e5;
  color: #6c757d;
}

.code-content-wrapper {
  padding: 20px;
  background: #f8f9fa;
}

.code-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
}

.code-label {
  font-size: 14px;
  font-weight: 600;
  color: #333;
}

.copy-code-btn {
  padding: 6px 14px;
  background: #3498db;
  color: white;
  border: none;
  border-radius: 6px;
  cursor: pointer;
  font-size: 13px;
  font-weight: 500;
  transition: all 0.3s ease;
  display: inline-flex;
  align-items: center;
  gap: 6px;
}

.copy-code-btn:hover {
  background: #2980b9;
  transform: translateY(-1px);
  box-shadow: 0 3px 8px rgba(52, 152, 219, 0.3);
}

.copy-code-btn i {
  font-size: 13px;
}

.code-block {
  margin: 0;
  padding: 16px;
  background: #2d2d2d;
  color: #f8f8f2;
  border-radius: 6px;
  overflow-x: auto;
  font-family: 'Courier New', Courier, monospace;
  font-size: 14px;
  line-height: 1.6;
  border: 2px solid #444;
}

.code-block code {
  white-space: pre;
  display: block;
}

.no-code-message {
  padding: 40px 20px;
  text-align: center;
  color: #999;
  background: #f8f9fa;
}

.no-code-message i {
  font-size: 32px;
  margin-bottom: 12px;
  display: block;
  color: #ccc;
}

.no-code-message p {
  margin: 0;
  font-size: 14px;
}

.no-data-message {
  padding: 80px 40px;
  text-align: center;
  color: #6c757d;
  background: linear-gradient(135deg, #f8f9fc 0%, #fff 100%);
  border-radius: 12px;
  margin: 20px;
}

.no-data-message i {
  font-size: 64px;
  margin-bottom: 24px;
  display: block;
  color: #dee2e6;
  filter: drop-shadow(0 4px 8px rgba(0, 0, 0, 0.08));
}

.no-data-message p {
  margin: 0;
  font-size: 17px;
  font-weight: 500;
  color: #6c757d;
  letter-spacing: 0.3px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .submission-modal {
    max-width: 95%;
    margin: 20px auto;
  }
  
  .submission-info-section {
    grid-template-columns: 1fr;
  }
  
  .code-card-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 12px;
  }
  
  .code-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 8px;
  }
  
  .copy-code-btn {
    width: 100%;
    justify-content: center;
  }
}
</style> 